Python Sets: "Apple" "Banana" "Cherry"
Python Sets: "Apple" "Banana" "Cherry"
Set
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not
allow duplicate values.
Unordered
Unchangeable
Example
print(thisset)
Get the Length of a Set
Example
print(len(thisset))
Example
Output
{'apple', 'banana', 'cherry'}
Example
for x in thisset:
print(x)
apple
banana
cherry
Add Items
Once a set is created, you cannot change its items, but
you can add new items.
thisset.add("orange")
print(thisset)
output
{'apple', 'cherry', 'orange', 'banana'}
Add Sets
To add items from another set into the current set, use
the update() method.
Example
thisset.update(tropical)
print(thisset)
Output
{'apple', 'mango', 'cherry', 'pineapple', 'banana',
'papaya'}
Add Any Iterable
The object in the update() method does not have to be
a set, it can be any iterable object (tuples, lists,
dictionaries etc.).
Example
thisset.update(mylist)
print(thisset)
output
Remove Item
To remove an item in a set, use the remove(), or
the discard() method.
Example
Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
output
{'cherry', 'apple'}
thisset.discard("banana")
print(thisset)
output
{'cherry', 'apple'}
Example
x = thisset.pop()
print(x)
print(thisset)
ouput
banana
{'cherry', 'apple'}
thisset.clear()
print(thisset)
output
set()
del thisset
print(thisset)
Loop Items
You can loop through the set items by using a for loop:
Example
for x in thisset:
print(x)
You can use the union() method that returns a new set
containing all items from both sets, or
the update() method that inserts all the items from one
set into another:
Example
set3 = set1.union(set2)
print(set3)
output
set1.update(set2)
print(set1)
output
{'b', 1, 'a', 3, 2, 'c'}