Professional Documents
Culture Documents
Set in Python
Set in Python
Rahul Das
Set is a type of sequence of elements that do
not allow duplicate values.
Syntax: set_name={s1,s2,....,sn}
Indexing is not possible in Set. Thus
subscript operator does not work on set.
Slicing operator also does not work on set.
Set is Mutable
S={10,20,30}
S={} #is not a set but a dictionary
S=set() #creating empty set
Creating set from other sequence
L=[1,2,3]
S=set(L)
Or
S=set(“Rahul”)
add() : This method is used to add elements
on a set.
◦ Add method randomly adds element in an index
◦ Adding duplicate value will make no changes in the
existing set.
update: This method returns the union of the
set and a sequence that was passed as
argument.
◦ Update method can take more than one sequence
of different type as an argument.
discard(): Removes the item passed as
argument
◦ If item not found in the set, it does not give error
message
remove(): This function also removes the item
passed as argument.
◦ If item not found in the set, it does gives error
message
intersection(): This method is used to find
Intersection between two set.
union(): This method is used to find union
between two set. Works same as update
function.
clear(): To remove all element from the set
issubset()
issuperset()
pop()
copy()
Write a Python script to count the distinct
elements of a List using a set.