4.3 Sets
A set represents unordered unique elements. Sets are created with {} or set().
Set properties
Sets have two important properties:
- Unordered: you cannot access a fixed position with an index.
- Unique: duplicate values are merged.
python
numbers = {1, 9, 2, 0, 0, 9}
print(numbers)The output order is not guaranteed, but the set keeps only one 0 and one 9.
Loading concept check...
Set operations
Sets support common mathematical operations:
- Intersection:
s1 & s2ors1.intersection(s2). - Union:
s1 | s2ors1.union(s2). - Difference:
s1 - s2ors1.difference(s2).
python
s1 = {1, 2, 3}
s2 = {3, 4, 5}
print(s1 & s2) # {3}
print(s1 | s2) # {1, 2, 3, 4, 5}
print(s1 - s2) # {1, 2}Loading interactive lab...
Removing duplicates from a list
Sets are often used to remove duplicates:
python
lst = [1, 9, 2, 0, 0, 9]
lst = list(set(lst))
print(lst)One possible output:
text
[0, 1, 2, 9]Note
After using
set() to remove duplicates, element order may not stay the same. If you need to preserve order, you can learn a steadier approach later.Loading concept check...
Loading practice...