Sets are the data structure in python like lists and tuples but the difference between set and other built-in data structures is that sets are used when we want to add unique elements because set does not allow repetition of elements.
Code:
mySet = {"apple", "banana", "pine apple", "apple"}
print(mySet)
In this code it will print apple just one time. Sets are unordered, unindexed and unchangeable.
Once a set is created we can not change the value of the item but we can add items to it.
Now let’s see what operations can we perform on sets? First let’s add some new items in our set. We use the add() function to add items to the set.
Code:
mySet = {"apple", 4 , True}
mySet.add("Covid")
print(mySet)
We can also add sets to sets but in this case the values present in both sets will be printed once. We use the update() function to add sets.
Code:
mySet = {"apple", 4 , True}
mySet1 = {1,2,3,4}
mySet.update(mySet1)
print(mySet)
We can also add other data structures to sets
Code:
mySet = {"apple", 4 , True}
mySet1 = [1,2,3,4]
mySet.update(mySet1)
print(mySet)
discard() and remove function is used to remove an item from the set
the pop() function is used to remove the last item of set
the clear() function is used to remove all items in sets and
del() function is used to delete the entire set
Let’s code each and every function and see their effect on program
Code:
myset = {"apple","banana","orange","pineapple"}
print(myset)
myset.pop()
print(myset)
myset.remove("apple")
print(myset)
myset.clear()
# This print statement will print an empty set
print(myset)
del(myset)
# This line will generate an error as no
# set named myset exist in program
print(myset)
Sets are unindexed and it is faster to check whether an item is present in a set or not.
Code:
myset = {"apple","banana","orange","pineapple"}
print("apple" in myset)
Let’s see some other operations on sets which we perform on sets in mathematics like union, intersection etc
For union of two sets we use ‘|’ operator
For intersection of two sets we use ‘&’ operator
For difference of two sets we use ‘-’ operator
And to get different values of both sets and ignore similar ones we use the ‘^’ operator. Now let’s write it in code for better understanding of these operators.
Code:
set1 = {1,2,3,4,5,6,7,8,9}
set2 = {1,3,5,7,9,10}
# this is for union
print(set1 | set2)
# for intersection
print(set1 & set2)
# difference of two sets
print(set1 -set2)
# set1 - set2 != set2 - set1
# those element which are not common in both sets
print(set1 ^ set2)
Key point: Use sets when you want uniqueness in Items
"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"
"Keep Learning and Keep exploring"
Love me like you do