SET

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?
  1. l = [10,20,30,40,10,20,10]
  2. s=set(l)
  3. print(s)
Important functions of set:
  1. add(x):
    Adds item x to the set
    Eg:
  2. s={10,20}
  3. s.add(40);
  4. update(x,y,z):
    To add multiple items to the set.

Eg:

  1. s={10,20,30}
  2. l=[40,50]
  3. 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:

  1. s={40,10,20}
  2. print(s)
  3. print(s.pop())
  4. print(s)
  5. Output
  6. {40, 10, 20}
  7. 40
  8. {10, 20}

clear():
To remove all elements from the Set.

  1. s={10,20,30}
  2. print(s)
  3. 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)
Python Set QUIZ