Unit 3 Topic Sets
Unit 3 Topic Sets
1.1 List
1.2 Tuples
1.3 Sets
1.4 Dictionaries
1
Sets in Python:
3.2.1 Defining Sets,
accessing values in Sets,
deleting values in Sets,
updating Sets.
3.2.2 Basic Set Operations
3.2.3 Built - in Set functions
# Difference between List, Tuple and set
# Advantages/features of sets
2
Sets in Python:
The set in python can be defined as the unordered collection
of various items enclosed within the curly braces i.e. { }.
The elements of the set can not be duplicate.
The Set is mutable but elements of set must be immutable.
However, the set itself is mutable. We can add or remove
items from it.
Sets can be used to perform mathematical set operations like
union, intersection, symmetric difference etc.
Unlike other collections in python, there is no index attached
to the elements of the set, i.e., we cannot directly access any
element of the set by the index.
However, we can print them all together or we can get the
list of elements by looping through the set.
3
Sets in Python:
Mathematically a set is a collection of items not in any
particular order.
A Python set is similar to this mathematical definition with
below additional conditions.
The elements in the set cannot be duplicates.
The elements in the set are immutable(cannot be modified) but the
set as a whole is mutable.
There is no index attached to any element in a python set.
So they do not support any indexing or slicing operation.
4
Sets in Python: Creating set
A set is created by placing all the items (elements) inside
curly braces {}, separated by comma.
E.g. set1={76,”kkwp”,’a’,21.30}
or by using the built-in function set().
E. g.
set2=set([45,67,23,90])
OR
set3=set((45,67,23,90))
OR
set4=set({45,67,23,90})
set() function allows only one parameter that may be single
element to be added or a list, a tuple or a set.
5
Sets in Python: Creating set
Sets can have any number of items and they may be of
different types (integer, float, tuple, string etc.).
But a set cannot have a mutable element, like list, set or
dictionary, as its element.
E. g.
set2={[34,67,12]} //Not allowed
But following is allowed
String = ‘hello’
set1 = set(String)
print(set1)
{'o', 'h', 'l', 'e’} #Output
6
Sets in Python: Creating Sets
A set contains only unique elements but at the time of set
creation, multiple duplicate values can also be passed.
Order of elements in a set is undefined and is unchangeable.
E.g
>>> b={3,2,1,2,2,3,1,1,3,2}
>>> b
{1, 2, 3}
OR
>>> set4=set({45,67,23,90})
>>> set4
{90, 67, 45, 23}
7
Sets in Python: Adding elements in Sets
We can add elements to a set by using add() method.
Again as discussed there is no specific index attached to the
newly added element.
>>> b={3,2,1,2}
>>> b.add(5,6) //multiple elements not allowed
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
>>> b.add(5)
>>> b
{1, 2, 3, 5}
8
Sets in Python: update elements in Sets
For addition of two or more elements Update() method
is used.
The update() method accepts lists, strings, tuples as well
as other sets as its arguments.
In all of these cases, duplicate elements are avoided.
Sets are mutable. But since they are unordered, indexing
have no meaning.
We cannot access or change an element of set using
indexing or slicing. Set does not support it.
E. g.
Months=set(["January","February", "March", "April", "May", "June"
])
Months.update(["July","August","September","October"]) 9
Sets in Python: Delete elements in Sets
Because a set isn’t indexed, you can’t delete an element
using its index.
So for this, you must use either discard() or remove()
method.
A method must be called on a set, and it may alter the set.
A particular item can be removed from set using methods,
discard() and remove().
The only difference between the two is that:
while using discard() if the item does not exist in the set, it
remains unchanged.
But remove() will raise an error in such condition i.e. a
KeyError arises if element doesn’t exist in the set.
10
Sets in Python: Delete elements in Sets
Months=set(["January","February","March","April","May"])
Months.discard(“May”)
print(Months)
{'March', 'February', 'June', 'January', 'April’} //O/P
Months.discard(“May”)
print(Months)
{'March', 'February', 'June', 'January', 'April’} //O/P
Months.remove(“May”)
print(Months)
Traceback (most recent call last):
File "H:\Python\setseg.py", line 17, in <module>
Months.remove(“May’’)
KeyError: ‘May’
11
Sets in Python: Accessing elements in Sets
Set items cannot be accessed by referring to an index, since sets
are unordered the items has no index.
But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in keyword.
(Use Membership Operator)
set1={56,34,12,89,59,90} s={1,2,3,4}
for i in s:
print(set1)
if i==2:
{34, 12, 56, 89, 90, 59} print("yes")
for s in set1: print(i, end=",")
print(s, end=",") else:
#O/P print("sorry")
34,12,56,89,90,59, #O/P
1,yes
2,3,4,sorry 12
Sets in Python: Built-in Methods
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
Removes an element from the set if it is a member. (Do
discard()
nothing if the element is not in set)
intersection() Returns the intersection of two sets as a new set
Updates the set with the intersection of itself and
intersection_update()
another
Removes an element from the set. If the element is not a
remove()
member, raise a KeyError
13
Sets in Python: Built-in Methods
Method Description
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
Removes and returns an arbitary set element. Raise
pop()
KeyError if the set is empty
Returns the symmetric difference of two sets as a
symmetric_difference()
new set
symmetric_difference_ Updates a set with the symmetric difference of
update() itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others
14
Sets in Python: Built-in Methods
set1={56,34,12,89,59,90} set1={56, 89, 90, 59}
set2={1,2,3,34}
set1.clear()
print(set1.isdisjoint(set2))
print(set1) True
set() set3={1,2,3,90}
_________________________________________________ print(set1.isdisjoint(set3))
set1={56,34,12,89,59,90} False
__________________________________________________
set2=set1.copy() Set1={56, 89, 90, 59}
print(set2) Set2={1, 2, 3}
{34, 56, 89, 90, 59, 12}. Set3={1, 2, 3, 90}
_________________________________________________ print(set2.issubset(set3))
set2.pop() True
34 print(set3.issuperset(set2))
True
print(set2)
print(set3.issubset(set2))
{56, 89, 90, 59, 12} False
15
Sets in Python: Built-in Operations
Union
Intersection
Difference
Subset
Check Membership
Iteration
16
Sets in Python: Built-in Methods
difference()
If A and B are two sets. The set difference of A and B is a set
of elements that exists only in set A but not in B.
For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
A - B = {1, 4} and B - A = {9}
Hence
A.difference(B)
returns A-B
And B.difference(A)
Returns B-A
17
Sets in Python: Built-in Methods
difference_update()
The syntax of difference_update() is:
A.difference_update(B)
O/P: A={1,4}
18
Sets in Python: Built-in Methods
intersection()
The intersection of two or more sets is the set of elements
which are common to all sets. For example:
A = {1, 2, 3, 4} B = {2, 3, 4, 9} C = {2, 4, 9, 10}
Then, A∩B = B∩A ={2, 3, 4}
The syntax of intersection() in Python is:
A.intersection(*other_sets)
The intersection() allows arbitrary
number of arguments (sets).
E.g. print(C.intersection(A, B))
OR print(A&B&C) is same
for both O/P: {2, 4}
19
Sets in Python: Built-in Methods
intersection_update()
The syntax of intersection_update() is:
A.intersection_update(*other_sets)
It only updates the set calling the intersection_update()
method.
Suppose,
A.intersection_update(B, C)
When you run the code,
result will be None
A will be equal to the intersection of A, B and C
B remains unchanged
C remains unchanged
20
Sets in Python: Built-in Methods
A = {1, 2, 3, 4}
B = {2, 3, 4, 9}
C = {2, 4, 9, 10}
print(C.intersection_update(A,B))
None
print(A)
{1, 2, 3, 4}
print(B)
{9, 2, 3, 4}
print(C)
{2, 4}
21
Sets in Python: Built-in Methods
symmetric_difference()
If A and B are two sets. The symmetric difference of A and B is
a set of elements that are uncommon in set A and in set B.
For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
Hence
A.symmetric_difference(B)=B.symmetric_difference(A)
returns
(A-B)+(B-A)
22
Sets in Python: Built-in Methods
symmetric_difference_update()
For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
Hence
A.symmetric_difference_update(B)
returns
A=(A-B)+(B-A)
i.e. {1,4,9}
23
Sets in Python: Built-in Methods
union()
If A and B are two sets. The union of A and B is a set of
elements that exists in set A as well as in B.
For example: If A = {1, 2, 3, 4} B = {2, 3, 9} Then,
Hence
A.union(B)
returns
A+B
i.e. {1,2,3,4,9}
24
Sets in Python: Built-in Functions
Function Description
Return True if all elements of the set are true (or if the set is
all()
empty).
Return True if any element of the set is true. If the set is
any()
empty, return False.
Return an enumerate object. It contains the index and value
enumerate()
of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
Return a new sorted list from elements in the set (does not
sorted() sort the set itself). E.g. sorted(s,reverse=True) will convert s
into List
25
sum() Return the sum of all elements in the set.
Sets in Python:
Built-in Functions –
>>> s1={45,23,78,0,12}
>>> all(s1)
False
>>> any(s1)
True
>>> sorted(s1)
[0, 12, 23, 45, 78]
>>> max(s1)
78
>>> min(s1)
0
>>> sum(s1)
158
>>> len(s1)
5
26
Sets in Python: Built-in Functions – enumerate()
Syntax: e.g.1
A = {11, 222, 33, 44}
enumerate(iterable, start=0) obj1=enumerate(A)
for i in obj1:
Parameters:
print (i);
Iterable: any object that supports iteration
Start: the index value from which the counter is
to be started, by default it is 0 Output
(0, 33)
(1, 11)
(2, 44)
(3, 222)
27
list in Python: Built-in Functions – enumerate()
e.g.2 e.g.3
l1 = ["eat","sleep","repeat"] l1 = ["eat","sleep","repeat"]
obj1 = enumerate(l1) obj1 = enumerate(l1)
print ("Return type:",type(obj1)) print ("Return type:",type(obj1))
print (list(enumerate(l1))) print (list(enumerate(l1,2)))
Output Output
Return type: <class 'enumerate'> Return type: <class 'enumerate'>
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')] [(2, 'eat'), (3, 'sleep'), (4, 'repeat')]
28
Sets in Python: Frozen Sets
Frozen set is just an immutable version of a Python
set object.
While elements of a set can be modified at any time,
elements of the frozen set remain the same after
creation.
While tuples are immutable lists, frozensets are immutable
sets.
Due to this, frozen sets can be used as keys in Dictionary
or as elements of another set.
Syntax:
f_set=frozenset(normal_set)
Sets in Python: Frozen Sets Methods
This datatype supports methods like
copy()
difference()
intersection()
isdisjoint()
issubset()
issuperset()
symmetric_difference()
union().
Being immutable it does not have method that add or remove
elements.
30
Sets in Python: Frozen Sets
>> s1={1,2,3,6,7}
>>> s2=frozenset(s1)
>>> type(s2)
<class 'frozenset'>
>>> s2
frozenset({1, 2, 3, 6, 7})
>>> >>> s2.add(90) #error
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
31
# Difference between List & Sets:
SN List Sets
The literal syntax of List is The literal syntax of the set is shown
1
shown by the [ ]. by the { }.
The set is mutable, but elements of
2 The List is mutable.
set are immutable.
List is a type of Ordered Sets is a type of unordered
3
collection collection
4 Supports indexing and Slicing Don’t Supports indexing and Slicing
Cant perform operations like
Can perform operations like union,
5 union, intersection and
intersection and difference
difference
6 List allows duplicates Duplication not allowed
32
# Difference between List & Tuple:
SN Sets Tuple
The literal syntax of List is The literal syntax of the tuple is
1
shown by the { }. shown by the ( ).
The set is mutable, but elements
2 The tuple is immutable.
of set are immutable.
Sets is a type of variable length The tuple has the fixed length and
3
and unordered collection ordered collection.
Don’t Supports indexing and
4 Supports indexing and Slicing
Slicing
Can perform operations like
Cant perform operations like
5 union, intersection and
union, intersection and difference
difference
6 Duplication not allowed Tuple allows duplicates
33
#Advantages of Sets:
Because sets cannot have multiple occurrences of the
same element, it makes sets highly useful to efficiently
remove duplicate values from a list or tuple and to
perform common math operations like unions and
intersections.
E.g.
>>> l=[2,3,4,5,2,3,4,5]
>>> s=set() #empty set creation.
>>> s=set(l)
>>> s
{2, 3, 4, 5}
34