☝️ Sets¶
1. Definition and Initialization¶
In Python, a set is an unordered collection of unique items. Sets are written with curly brackets.
# set of integers
s1 = {1, 2, 3, 4, 5}
print(s1) # prints: {1, 2, 3, 4, 5}
# set automatically removes duplicates
s2 = {1, 2, 2, 3, 4, 4, 5}
print(s2) # prints: {1, 2, 3, 4, 5}
# we can make a set from a list
s3 = set([1, 2, 2, 3, 4, 4, 5])
print(s3) # prints: {1, 2, 3, 4, 5}
2. Accessing Set Items¶
You cannot access or change an element of a set using indexing or slicing. Set data type does not support it.
s1 = {1, 2, 3, 4, 5}
print(s1[1]) # raises TypeError: 'set' object is not subscriptable
3. Add Items¶
To add one item to a set, we use the add()
method. To add more than one item, we use the update()
method.
s1 = {1, 2, 3, 4, 5}
s1.add(6)
print(s1) # prints: {1, 2, 3, 4, 5, 6}
s1.update([7, 8, 9])
print(s1) # prints: {1, 2, 3, 4, 5, 6, 7, 8, 9}
4. Remove Item¶
To remove an item in a set, we can use the remove()
, or the discard()
method.
s1 = {1, 2, 3, 4, 5}
s1.remove(1)
print(s1) # prints: {2, 3, 4, 5}
If the item to remove does not exist, remove() will raise an error.
s1.remove(7) # raises KeyError: 7
# If the item to remove does not exist, discard() will NOT raise an error.
s1.discard(7)
print(s1) # prints: {2, 3, 4, 5}
5. Set Operations¶
You can perform operations like union, intersection, difference, and symmetric difference on sets.
s1 = {1, 2, 3, 4, 5}
s2 = {4, 5, 6, 7, 8}
print(s1.union(s2)) # prints: {1, 2, 3, 4, 5, 6, 7, 8}
print(s1.intersection(s2)) # prints: {4, 5}
print(s1.difference(s2)) # prints: {1, 2, 3}
print(s1.symmetric_difference(s2)) # prints: {1, 2, 3, 6, 7, 8}
6. Length of a Set¶
You can get the number of items in a set with the len()
function.
s1 = {1, 2, 3, 4, 5}
print(len(s1)) # prints: 5
7. Check if Item Exists¶
To determine if an item exists in a set, you can use the in
keyword.
s1 = {1, 2, 3, 4, 5}
print(3 in s1) # prints: True
print(6 in s1) # prints: False
8. Clear a Set¶
To remove all items in a set, you can use the clear()
method.
s1 = {1, 2, 3, 4, 5}
s1.clear()
print(s1) # prints: set()
9. Set Comprehensions¶
Similar to lists, set comprehensions provide a concise way to create sets.
# create a set of squares for numbers from 0 to 9
squares = {x**2 for x in range(10)}
print(squares) # prints: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}