- unordered**(unindexed)
- unchangeable(possible to remove & add)
- do not allow duplicate values
thisset = {"apple", "banana", "cherry"}
# any data types
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # {'cherry', 'banana', 'apple'}
Constructor: set(())
thisset = set(("apple", "banana", "cherry"))
print(thisset) # {'cherry', 'banana', 'apple'}
Access Set Items
# for...in
for x in thisset:
print(x)
# check
print("banana" in thisset) # True
Add Set Items
thisset = {"apple", "banana", "cherry"}
# add()
thisset.add("orange")
print(thisset) # {'cherry', 'banana', 'orange', 'apple'}
# Add Sets: update()
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
# {'papaya', 'pineapple', 'mango', 'cherry', 'banana', 'apple'}
# add any iterable
mylist = ["kiwi", "orange"]
thisset.update(mylist)
Join Sets
# union(): returns a new set containing all items from both sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
# update(): inserts all the items from one set into another
set1.update(set2)
# Keep ONLY the Duplicates: intersection_update()
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
# intersection()
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
# Keep All, But NOT the Duplicates: symmetric_difference_update()
x.symmetric_difference_update(y)
# symmetric_difference()
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
Remove Set Items: remove(), discard()
# If the item to remove does not exist, remove() will raise an error
thisset.remove("banana")
# If the item to remove does not exist, discard() will NOT raise an error.
thisset.discard("banana")
# Remove the last item
x = thisset.pop()
# Remove all items
clear()
thisset.clear()
# del keyword: delete set variable
del thisset
Loop Sets
# for ...
for x in thisset:
print(x)