Sets
Construct a Set
a = {"John", "Tom"} # {'Tom', 'John'}
# duplicate values will be merged
b = {"John", "Tom", "John"} # {'Tom', 'John'}
# from a list or any other iterable collection
c = set([1, 3, 5]) # {1, 3, 5}
# from set comprehension
d = {x for x in range(10)} # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Loop Through Items
a = {"fig", "mango", "watermelon"}
for e in a:
print(e)
Add Item
a = {"fig", "mango", "watermelon"}
a.add("grape")
print(a) # {'grape', 'fig', 'mango', 'watermelon'}
Check If Item Exists
a = {"fig", "mango", "watermelon"}
print("fig" in a) # True
print("cherry" in a) # False
Set's Common Methods
clear
a = {"fig", "mango", "watermelon"}
a.clear()
print(a) # set()
difference
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a but not in b
print(a.difference(b)) # {'watermelon', 'fig'}
print(a - b) # {'watermelon', 'fig'}
intersection
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in both a and b
print(a.intersection(b)) # {'mango'}
print(a & b) # {'mango'}
isdisjoint
a = {1, 3, 5}
b = {2, 4}
c = {1, 6}
print(a.isdisjoint(b)) # True
print(a.isdisjoint(c)) # False
issubset
a = {1, 3, 5}
b = {2, 4}
c = {1, 3}
print(b.issubset(a)) # False
print(c.issubset(a)) # True
symmetric_difference
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a or b but not both
print(a.symmetric_difference(b)) # {'fig', 'blueberry', 'watermelon'}
print(a ^ b) # {'fig', 'blueberry', 'watermelon'}
union
a = {"fig", "mango", "watermelon"}
b = {"mango", "blueberry"}
# fruit in a or b or both
print(a.union(b)) # {'watermelon', 'blueberry', 'mango', 'fig'}
print(a | b) # {'watermelon', 'blueberry', 'mango', 'fig'}
Code Challenge
Try to modify the code provided in the editor to make a set like
{frozenset({'bar', 'foo', 'baz'}), 1}
.
Loading...
> code result goes here