Click Here

Set in Python

Set is a collection that is unordered.

mySet={"Delhi","NewYork","Sydeny"}
print(mySet)

  Output:
  (‘NewYork’, ‘Delhi’, ‘Sydeny’) Any random order elements may be displayed

Some important methods that can be applied on set are following.

1) add(): This add an element to the set but does not add if element set has element already.

mySet={"Delhi","NewYork","Sydeny"}
mySet.add("Mumbai")
print(mySet)

   Output:
   set([‘NewYork’, ‘Sydeny’, ‘Delhi’, ‘Mumbai’])

output may vary as set is not ordered.

2) remove(): It removes the specific element from set.
                      eg: mySet.remove(“Delhi”)

mySet={"Delhi","NewYork","Sydeny"}
mySet.remove("Delhi")
print(mySet)

   Output:
   set([‘NewYork’, ‘Sydeny’])

3) pop(): It returns the any random item from the set
                eg: mySet.pop()

mySet={"Delhi","NewYork","Sydeny"}
print(mySet.pop())
print(mySet)

   Output:    Sydeny (in case it popped Sydeny)

set([‘ ‘Delhi’, ‘Mumbai’])  

4)clear(): It removes all the elements from given set mySet.clear()

mySet={"Delhi","NewYork","Sydeny"}
mySet.clear()
print(mySet)

   Output:
set([])    – blank set as there is no element in set after clear

5)len(): It gives the length of set means how many elements are in the set 

mySet={"Delhi","NewYork","Sydeny"}
print(len(mySet))

   Output:    3 [as there are three elements in the list]

6)del(): We can not delete an element from set using del() but we can delete the complete set as following example.

mySet={"Delhi","NewYork","Sydeny"}
del(mySet)
print(mySet)

   Output:    error  [as set is deleted and not exists any more]

Click Here

Video/ C Introduction

Watch video in full size