3.4 Set Basics¶
- A set is an unordered collection of unique elements. Sets have the following properties:
- Elements are unordered: Elements in the set do not have a position or index.
- Elements are unique: No elements in the set share the same value.
- A set can be created using the set() function, which accepts a sequence-type iterable object (list, tuple, string, etc.)
-
A set literal can be written using curly braces { } with commas separating set elements.
- set literals execute twice as quickly
-
an empty set can only be created using set()
- index operator is not valid cause the set is unordered and positions don't matter
# Initial list contains some duplicate values
first_names = [ 'Harry', 'Hermione', 'Ron', 'Harry', 'Albus', 'Ron', 'Ron' ]
# Creating a set removes any duplicate values
names_set = set(first_names)
print(names_set)
Modifying Sets¶
- Sets are mutable, elements can be added or removed.
- The add() method places a new element into the set if the set does not contain an element with the provided value.
- set.add(value): Add value into the set. Ex: my_set.add('abc')
- The remove() and pop() methods remove an element from the set.
- set.remove(value): Remove the element with given value from the set. Raises KeyError if value is not found. Ex: my_set.remove('abc')
- set.pop(): Remove a random element from the set. Ex: my_set.pop()