Python Sets
Sets allow multiple values to be stored as a collection.
- The collection of values in a set can be changed after it has been initialised. Sets
are mutable (the exception is if you use
frozenset()
to create an immutable set). - The values in a set must be immutable and hashable. This means you can't have a set of sets
- The values in a set are unordered, meaning they cannot be accessed in a consistent order or accessed by an index.
- The values cannot be accessed by a key (unlike a dictionary).
- Sets cannot have repeated items. Each item in a set can only appear once.
Example: Creating a Set
Python
Copy Code
types = { 'Motorbike', 'Car', 'Truck' } print(types)
Output
{ 'Motorbike', 'Car', 'Truck' }
Example: Using the set constructor
Python
Copy Code
# Pass in a set to the "set()" constructor. types = set( {'Motorbike', 'Car', 'Truck'} ) # note the curly brackets # Pass in a tuple to the "set()" constructor. types = set( ('Motorbike', 'Car', 'Truck') ) # note the double parentheses
Example: Creating a Set wuth one element
One would assume that creating a Tuple one element was as simple as
Python
Copy Code
types = { 'Motorbike' } print(types) print(type(types))
Output
{ 'Motorbike' } <class 'set'>
Notes
A Tuple can contain any type of object, and can mix and match object types.
Example: Mixing types in a Set
Python
Copy Code
# A Set containing a string, a number and a Tuple mixedBag = { 'string', 42, (1,2,3) }
Output
{ 'string', (1,2,3), 42 }
Notice that the output has the elements in the set in a different order than it was defined.