Search This Blog

Set in Python

Set is a collection of finite elements ,It does not contain any sequence(index) hence we can display set elements randomly.

Set always display unique elements ,It will be declared using    {}.


x = {"C","CPP","DS","PHP","Java",".NET"}



Example of Set:-

x = {"C","CPP","DS","PHP","Java",".NET","C","CPP"}
for data in x:
   print(data)



Where we use set in python:-

1) When we want to display random elements then we can use set


2)  When we want to display unique elements then we can use set


for example OTP is random number it can be implemented by Set.


Predefined Method Of Set:-

x = {"C","CPP","DS","PHP","Java",".NET","C","CPP"}
1)  add() :-   It is used to add elements in set
      x.add("PYTHON")
2)  remove():-  It is used to remove element in set
      x.remove("C")
3)  max(),min():-  it return max and minimum element
     print(max(x))
     print(min(x))

4) sum():-    It it is used to calculate sum of set elements

     print(sum(x))

5)   union() :-   It is used to combine two different subset in set.

     a = {1,2,3,4}
    b =  {2,3,7,8,9}
    c= a.union(b)

6)  intersection():- It will return common elements from set
      a = {1,2,3,4}
      b =  {2,3,7,8,9}
      c= a.intersection(b)


7) difference():-   It is used to use minus operation in set means the elements which will be exist under x will be removed from y.

      a = {1,2,3,4}
      b =  {2,3,7,8,9}
      c= a.difference(b)

   

Complete Example of Set Using Program:-

x = {1,12,23,34,45,11,3}
y = {2,3}
x.add(9)
x.remove(1)
print(max(x))
print(min(x))
print(sum(x))
print(x.union(y))
print(y.union(x))
print(x.intersection(y))
print(x.difference(y))
print("data is ")
for data in x:
   print(data)
 

ASSIGNMENT of SET:-
1)  WAP to find max element in set ?

2)  WAP to reverse set elements?
      s={3,11,23,34,56,1,78,19,17,98,1}

s1 = [int]*len(s)
c=0
for i in s:
   s1[c]=i
   c=c+1
for i in range(len(s)-1,-1,-1):
  print(s1[i])


3)  WAP to display prime element in Set?







Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post