Python Set
Set is an unordered and unindexed collection of values or elements which do not allow duplicate values and are placed within the curly braces.
Example
names = {"Jonny", "Danny", "Kelly", "Jane"}
print(names)
Output
Loop Through Set
To access the items or elements of a set, you can use the for loop.
Example
names = {"Jonny", "Danny", "Kelly", "Jane"}
for i in names:
print(i)
Output
Jane
Jonny
Kelly
Add Items in set
To add items in a Set, you can use the add() method.
Example
names = {"Jonny", "Danny", "Kelly", "Jane"}
names.add("Peter")
print(names)
Output
Update Items in set
The update() method adds items from one set in a Set.
Example
fruits = {"apple", "banana", "mango", "grapes"}
fruits.update({"watermelon", "guava", "cherry"})
print(fruits)
Output
The set() constructor
The set() constructor is used to create a new set.
Example
foods = (("bread", "butter", "milk", "egg"))
print(foods)
Output
Length of Set
You can use the len() function to get the the number of items present in a set.
Example
foods = {"bread", "butter", "milk", "egg"}
print(len(foods))
Output
Remove Item from a set
The remove() function removes item from a set.
Example
foods = {"bread", "butter", "milk", "egg"}
foods.remove("butter")
print(foods)
Output
Discard Item from a set
The discard() function also removes the specified item from a set.
Example
foods = {"bread", "butter", "milk", "egg"}
foods.discard("milk")
print(foods)
Output
Pop Item
The pop() function also removes the last item from a set. Since, a set items are unordered, so you cannot determined which item will get removed. The pop() functions returns the removed item .
Example
foods = {"bread", "butter", "milk", "egg"}
x = foods.pop()
print(x)
Delete set
The del keyword deletes the set.
Example
foods = {"bread", "butter", "milk", "egg"}
del foods
print(foods)
Output
Clear set items
The clear() method empties items from a set.
Example
foods = {"bread", "butter", "milk", "egg"}
foods.clear()
print(foods)
Output
Join two sets
The union() method and update() method combines all items of sets.
Example
set1 = {"bread", "butter", "milk", "egg"}
set2 = {"fish", "meat"}
set3 = set1.union(set2)
print(set3)
Output
The update() method inserts items from set2 to set1.
Example
set1 = {"bread", "butter", "milk", "egg"}
set2 = {"fish", "meat"}
set1.update(set2)
print(set1)
Output
Check If an Item Exists
You can use the in keyword to check if an item exists in a set.
Example
foods = {"bread", "butter", "milk", "egg"}
if "butter" in foods:
print("butter exist")