python1-1

Sets in Python

A Set in Python is a data structure that contains an un-ordered collection of
distinct objects. A set in python is similar to sets in mathematics.

Use Case : removing duplicates from a sequence, performing mathematical operations like
Union , Intersection, difference etc.

Set Types: There are two builtin set types: set and frozenset.
The set type is mutable i.e its elements can be changed ,
Since it is mutable so it can not be used as key in dictionary.
The frozentype is immutable and hashable, so it can be used as dictionary key.

Note: Sets do not support indexing, slicing.

Creation of a set:
Lets say we are creating a set A from a list of elements which has duplicate elements as below:
A = set([1,2,3,3,4,5,2,1,6])
print(A);
{1, 2, 3, 4, 5, 6}

Note set A created contains only unique elements of input list.

Add elements in a set:
A.update([7,8,9,6])
print(A)
{1, 2, 3, 4, 5, 6, 7, 8, 9}


Lets Create a frozenset
B= frozenset([4,5,6,7,5])
print(B)
frozenset({4, 5, 6, 7})


If we try to update a frozen set, we get an error
B.update([7,8,9,6])
Error:
AttributeError: 'frozenset' object has no attribute 'update'



Set Operations
Lets say we have captured favourite sports of Raj and Riya in two sets.

raj = {'Cricket', 'Soccer','Badminton','Tennis','Boxing'}
print(raj);
{'Tennis', 'Soccer', 'Boxing', 'Badminton', 'Cricket'}


riya = {'Badminton','Tennis','Chess','Cycling'}
print(riya);
{'Badminton', 'Tennis', 'Chess', 'Cycling'}


Which sports is liked by both raj and riya?
Syntax: Set1.Intersection(Set2)
raj.intersection(riya)
{'Badminton', 'Tennis'}

Which sports only raj likes ?
Syntax: Set1.difference(Set2)
print(raj.difference(riya))
{'Soccer', 'Boxing', 'Cricket'}

Which sports only riya likes but not raj ?
riya.difference(raj)
{'Chess', 'Cycling'}

Which sports are liked by either riya or raj , but not both?
Syntax: Set1.symmetric_difference(Set2)
raj.symmetric_difference(riya)
{'Boxing', 'Chess', 'Cricket', 'Cycling', 'Soccer'}


Shekhar Pandey

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.