Python Sets
Python Sets
BCSG0001
Which data type we will use to store a set/list of pin code of any state (UP).
Which data type we will use to store a set/list of pin code of any state (UP).
Answer: Set
reason: -pin code can not be duplicates.
-pin code can not be change.
-we can add or remove any pin code.
St = { }
Creating a Set This is not an empty set.
It’s a dictionary.
print(St)
print(St)
Can we have duplicates in a set..?
st = {1,2,3,4,2,2,1,0,-1}
//creating a set
print(st)
{1, 2, 3, 4, 0, -1}
Size of a Set
s = set() s = {1,2,3,4,5,6}
print(len(s)) print(len(s))
0 6
Accessing elements
s = {1,2,3,4}
print(s[0])
We cant not access the elements because sets are unordered.( indexing can not be performed)
Accessing elements
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a specified value is present in a set,
by using the in keyword.
s = {1,2,3,4}
for i in s:
print(i)
3
2
1
4
Once a set is created, you cannot change its items, but you can add new items.
Adding elements in a set Using add() method
To add one item to a set use the add() method.
St = set()
St.add(1)
St.add(2)
St.add(3)
St.add(4)
Print(St)
{1,2,3,4}
Adding elements in a set Using update() method
To add items from another set into the current set, use the update() method.
union()
update()
intersection()
intersection_update()
symmetric_difference()
symmetric_difference_update()
Join sets – union()
Returns a new set containing all items from both sets.
Join sets – update()
To add items from another set into the current set, use the update() method.
Join sets – update()
To add items from another set into the current set, use the update() method.
Note: Both union() and update() will exclude any duplicate items.
Join sets – intersection()
Return a new set, that only contains the items that are present in both sets.
Join sets – intersection_update()
No return.
Join sets – symmetric_difference()
Return set.
Join sets – symmetric_difference_update()
No return.
Set methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set