Set
- unordered
- unchangeable(cannot change the items after the set has been created)
- unindexed
- do not allow duplicate
Note
Set items are unchangeable, but you can remove items and add new items.
thisset = {"apple", "banana", "cherry"}
len()
Set Items
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
type()
< class 'set'>
constructor
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Access Items
value
in
thisset
Adding
add()
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
Add items from another set
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
Note
update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.)
Removing
- remove()
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Note
If the item to remove does not exist, remove() will raise an error.
- discard()
thisset.discard("banana")
Note
If the item to remove does not exist, discard() will NOT raise an error.
- pop() - del last
- clear() - empties the set
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
- del - delete the set completely
del thisset
Join Two Sets
both will exclude any duplicate items.
- union - ret. new set
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
- update
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Keep ONLY the Duplicates
- intersection_update() - present in both
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
- intersection() - new set, present in both
Keep All, But NOT the Duplicates
- symmetric_difference_update() - are NOT present in both
- symmetric_difference() - a new set, NOT present in both