- If the user wants to represent a group of unique values as a single entity then the user should go for the set.
- In set, Duplicates are not allowed like in Java. Insertion order is also not preserved.
- Indexing and slicing are alse not allowed for the set.
- Set objects are mutable.
How will you create Set?
- l = [10,20,30,40,10,20,10]
- s=set(l)
- print(s)
Important functions of set:
- add(x):
Adds item x to the set
Eg: - s={10,20}
- s.add(40);
- update(x,y,z):
To add multiple items to the set.
Eg:
- s={10,20,30}
- l=[40,50]
- s.update(l,range(5))
copy():
Returns copy of the set.
It is cloned object.
pop():
It removes and returns some random element from the set.
Eg:
- s={40,10,20}
- print(s)
- print(s.pop())
- print(s)
- Output
- {40, 10, 20}
- 40
- {10, 20}
clear():
To remove all elements from the Set.
- s={10,20,30}
- print(s)
- s.clear()
1.union():
x.union(y)
intersection():
x.intersection(y) or x&y
Returns common elements present in both x and y
difference():
x.difference(y)
set objects won’t support indexing and slicing:
Eg:
s={10,20,30,40}
print(s[0]) ==>TypeError: ‘set’ object does not support indexing
print(s[1:3]) ==>TypeError: ‘set’ object is not subscriptable
Create an empty set. Write a program that adds two new names to this set, modifies one existing name, and deletes one name existing in it.
s = set()
s.add('vikas')
s.add('ram')
s.remove('vikas')
s.add('Alex')
s.remove('ram')
Write a program to create a set of 5 randomly generated numbers in the range 10 to 30. Find how many of these numbers are less than 20. Delete all numbers which are greater than 25.
s = set()
while True:
s.add(random.randint(10, 30))
if len(s) == 5:
break
print('set:', s)
t = set()
count = 0
for item in s:
if item < 20:
count += 1
if item <= 25:
t.add(item)
s = t
print('Count of nos. less than 20:', count)
print('Set after deleting elements > 25: ', s)