Alphalearningschool
        

<<< Prev

Next >>>

Up
Python Set

A set object is an unordered collection of distinct hash able objects. It is commonly used in membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Sets support x in the set, len(set), and for x in set like other collections. Set is an unordered collection and does not record element position or order of insertion. Sets do not support.

Create a set in Python:

#A new empty set
setx = set()
print(setx)
set()
#A non empty set
n = set([0, 1, 2, 3, 4, 5])
print(n)

O/P-
set()
{0, 1, 2, 3, 4, 5}

 

Iteration Over Sets:

We can move over each of the items in a set using a loop. However, since sets are unordered, it is undefined which order the iteration will follow.

num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
    print(n)

O/P-
0
1
2
3
4
5

 

Add member(s) in Python set: 

#A new empty set
color_set = set()
#Add a single member
color_set.add("Red")
print(color_set)
{'Red'}
#Add multiple items
color_set.update(["Blue", "Green"])
print(color_set)

O/P-
{'Red'}
{'Green', 'Blue', 'Red'}

 

Remove item(s) from Python set:

pop(), remove() and discard() functions are used to remove individual item from a Python set. See the following examples :

pop() function:

num_set = set([0, 1, 2, 3, 4, 5])
num_set.pop()
0
 print(num_set)
Output:
{1, 2, 3, 4, 5}

num_set.pop()
1
print(num_set)
   
Output:  
{2, 3, 4, 5}

 

remove() function: 

num_set = set([0, 1, 2, 3, 4, 5])
 num_set.remove (0)
print(num_set)
Output: {1, 2, 3, 4, 5}

 

discard() function:

num_set = set([0, 1, 2, 3, 4, 5])
num_set.discard(3)
print(num_set)
Output:{0, 1, 2, 4, 5}

 

Intersection of sets:

In mathematics, the intersection A ∩ B of two sets A and B is the set that contains all elements of A that also belong to B (or equivalently, all elements of B that also belong to A), but no other elements.

#Intersection
 setx = set(["green", "blue"])
 sety = set(["blue", "yellow"])
 setz = setx & sety
 print(setz)
Output: {'blue'}

Union of sets:

In set theory, the union (denoted by ∪) of a collection of sets is the set of all distinct elements in the collection. It is one of the fundamental operations through which sets can be combined and related to each other.

#Union
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
seta = setx | sety
print (seta)
Output: {'yellow', 'blue', 'green'}

 

Set difference:

 setx = set(["green", "blue"])
 sety = set(["blue", "yellow"])
 setz = setx & sety
 print(setz)
 Output:{'blue'}
#Set difference
 setb = setx - setz
 print(setb)
 Output: {'green'}

 

Symmetric difference:

setx = set(["green", "blue"])
 sety = set(["blue", "yellow"])
#Symmetric difference
setc = setx ^ sety
print(setc)
Output: {'yellow', 'green'}

 

issubset and issuperset:

  setx = set(["green", "blue"])
  sety = set(["blue", "yellow"])
  issubset = setx <= sety
  print(issubset)
	Output: False
 issuperset = setx >= sety
  print(issuperset)
  Output: False

Difference between Discard () and remove () Function:

The discard () and remove () function both are perform same but one major difference is if we use the discard () method and passing argument and if it is not in set that time python will not throw any error but in remove () it will throw error.

Let see with example: 

days={"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
year=set(["Jan","Feb","Mar","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"])

days.discard("Jan");
print(days)
days.remove("Jan")
print(days)
#Same as with set method it will work

O/P
Traceback (most recent call last):
  File "D:/New folder/PycharmProjects/Loops/Set2.py", line 6, in <module>
    days.remove("Jan")
KeyError: 'Jan'
{'Thu', 'Tue', 'Wed', 'Sun', 'Mon', 'Fri', 'Sat'}

 

FrozenSets:

Frozen sets are immutable for the normal sets it is like we cannot change after the initialize.

In this frozen sets we cannot use any inbuilt function of set like add () , remove () etc..

We can use frozen set as key in dictionary.

Let see example: 

Ex.
a=frozenset(["abc","dfg","cdf"])
print(a)
print(type(a))

O/p
frozenset({'abc', 'cdf', 'dfg'})
<class 'frozenset'>

 

Use frozenset () in dictionary: 

employee={"name : ram","designation : software-developer" ,"age : 25","salary : 300000","sex : male"}
fset=frozenset(employee);
print(fset)

O/p
frozenset({'name : ram', 'designation : software-developer', 'salary : 300000', 'age : 25', 'sex : male'})

More  examples :

  setx = set(["green", "blue"])
   sety = set(["blue", "green"])
  issubset = setx <= sety
  print(issubset)
   Output: True
   issuperset = setx >= sety
   print(issuperset)
Output: True

 

Shallow copy of sets:

setx = set(["green", "blue"])
 sety = set(["blue", "green"])
 #A shallow copy
 setd = setx.copy()
 print(setd)
Output: {'blue', 'green'}

 

Clear sets:

setx = set(["green", "blue"])
#Clear AKA empty AKA erase
sete = setx.copy()
sete.clear()
print(sete)
Output: set()