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])
{1, 2, 3, 4, 5, 6}

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

Add elements in a set:
{1, 2, 3, 4, 5, 6, 7, 8, 9}

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

If we try to update a frozen set, we get an 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'}
{'Tennis', 'Soccer', 'Boxing', 'Badminton', 'Cricket'}

riya = {'Badminton','Tennis','Chess','Cycling'}
{'Badminton', 'Tennis', 'Chess', 'Cycling'}

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

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

Which sports only riya likes but not raj ?
{'Chess', 'Cycling'}

Which sports are liked by either riya or raj , but not both?
Syntax: Set1.symmetric_difference(Set2)
{'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.