Page 202 -
P. 202
factory functions
Remove duplicates with sets
In addition to lists, Python also comes with the set data structure, which
behaves like the sets you learned all about in math class.
The overriding characteristics of sets in Python are that the data items in a set
are unordered and duplicates are not allowed. If you try to add a data item to a set
that already contains the data item, Python simply ignores it.
Create an empty set using the set() BIF, which is an example of a factory
function:
Create a new,
empty set, and
assign it to a distances = set()
variable.
It is also possible to create and populate a set in one step. You can provide a list
of data values between curly braces or specify an existing list as an argument
to the set() BIF, which is the factory function:
Any duplicates in
the supplied list
distances = {10.6, 11, 8, 10.6, "two", 7} of data values are
ignored.
Any duplicates in distances = set(james)
the “james” list are
ignored. Cool.
Factory Function: A factory function is used to make new
data items of a particular type. For instance, “set()” is
a factory function because it makes a new set. In the
real world, factories make things, hence the name.
166 Chapter 5