0% found this document useful (0 votes)
18 views62 pages

UNIT-III - Part-3 (Dict and Sets)

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, methods for accessing and modifying elements, and the creation of nested dictionaries. It explains how to loop through dictionaries and utilize built-in functions and methods for various operations. Additionally, it covers dictionary membership tests and the significance of immutability for keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views62 pages

UNIT-III - Part-3 (Dict and Sets)

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, methods for accessing and modifying elements, and the creation of nested dictionaries. It explains how to loop through dictionaries and utilize built-in functions and methods for various operations. Additionally, it covers dictionary membership tests and the significance of immutability for keys.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Python Programming for Problem

Solving

Unit-3

Department of Electrical and Electronics Engineering 1


Data structures - Dictionaries

Department of Electrical and Electronics Engineering


Dictionaries
• Dictionaries are used to store data values in pairs (key, value).
• In one sentence, dictionaries are pairs (key, value). Sometimes
they are called maps.
• A dictionary is a collection which is ordered*, changeable and
does not allow duplicates. (*From Python version 3.7,
dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.)
• Dictionary elements are presented in key:value pairs, and can
be referred to by using the key name.
• In Python dictionaries are written with curly brackets – { }
• Syntax: my_dict = {key0 : value0, key1 : value1,
..., keyn : valuen}
Department of Electrical and Electronics Engineering
Dictionaries

• Dictionaries are of type dict.


• Since they have a type, they can be assigned to a variable.
• To refer to a value associated with a key in a dictionary we use
dictionary_name[key]
• Dictionary keys must be immutable, but the values can be
anything (except None).
• Once you've created a dictionary you can add key-value pairs
by assigning the value to the key.
• Syntax: dictionary_name[key] = value
• Keys must be unique.

Department of Electrical and Electronics Engineering


Creating a Dictionary

• Creating a dictionary is as simple as placing items inside curly


braces {} separated by comma.
• An element in a dictionary can be expressed as a key: value
pair,
Ex:
1. Empty dictionary:
my_dict = {}
2. Dictionary with integer keys:
my_dict = {1: 'apple', 2: 'ball'}
3. Dictionary with mixed keys:
my_dict = {'name': 'John', 1: [2, 4, 3]}

Department of Electrical and Electronics Engineering


Creating a Dictionary

•A dictionary can also be created using dict() constructor.


Ex:
1. my_dict = dict()
2. my_dict = dict({1: 'apple', 2: 'ball'})
3. my_dict = dict([(1,'apple‘), (2,'ball‘)])

Department of Electrical and Electronics Engineering


Accessing elements from a Dictionary

• The elements of a dictionary can be accessed by referring to its


key name, inside square brackets or with the get() method.
• The difference while using get() is that it returns None instead
of KeyError, if the key is not found.
Ex:
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name']) // Jack
print(my_dict.get('age')) // 26
my_dict.get('address') // No error
my_dict['address'] // Key Error

Department of Electrical and Electronics Engineering


Accessing keys of a Dictionary
• The keys of a dictionary can be accessed by the keys() method.
• The keys() method will return a list of all the keys in the dictionary.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.keys()
print(x)
• The list of the keys is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the keys list.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.keys()
print(x)
my_dict[“address”] = “India”
print(x)
Department of Electrical and Electronics Engineering
Accessing values of a Dictionary
• The values in a dictionary can be accessed by the values() method.
• The keys() method will return a list of all the values in the dictionary.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.values()
print(x)
• The list of the values is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the values list.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.values()
print(x)
my_dict[“age”] = 36
print(x)
Department of Electrical and Electronics Engineering
Accessing items of a Dictionary
• The elements in a dictionary can be accessed by the items() method.
• The items() method will return a list of all the elements(items) in the
dictionary.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.items()
print(x)
• The returned list is a view of the items of the dictionary, meaning that any
changes done to the dictionary will be reflected in the items list.
Ex:
my_dict = {'name':'Jack', 'age': 26}
x = my_dict.items()
print(x)
my_dict[“age”] = 36
Print(x)
Department of Electrical and Electronics Engineering
Nested Dictionary
• A nested dictionary can also be created as shown in diagram.

Ex:
my_dict = {1:‘Hello', 2:‘Hi',
3:{'A':'Welcome', 'B':'To', 'C':‘Vignan'}}
print(my_dict)
Department of Electrical and Electronics Engineering
Nested Dictionary
A nested dictionary can also be created as.
Ex:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Department of Electrical and Electronics Engineering
Nested Dictionary
A nested dictionary can also be created as.
Ex:
child1 = {
"name" : "Emil",
"year" : 2004 myfamily = {
} "child1" : child1,
child2 = { "child2" : child2,
"name" : "Tobias", "child3" : child3
"year" : 2007 }
}
child3 = {
"name" : "Linus",
"year" : 2011
}

Department of Electrical and Electronics Engineering


Accessing elements of a nested Dictionary

• In order to access the value of any key in nested dictionary, use indexing
[] syntax.
Ex:
my_dict = {'D1':{1:‘Hello'},'D2':{'Name':‘Vignan'}}
print(my_dict['D1'])
print(my_dict['D1'][1])
print(my_dict['D2']['Name'])

Department of Electrical and Electronics Engineering


Loop through a dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Ex: Print all key names in the dictionary, one by one
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict:
print(x)
Ex: Print all values in the dictionary, one by one
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict:
print(mydict[x])

Department of Electrical and Electronics Engineering


Loop through a dictionary using methods
• There are methods to return the individual keys, values and items of a dictionary.
Ex: The keys() method, return keys of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict.keys():
print(x)
Ex: The values() method, return values of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict.values():
print(x)
Ex: The items() method, return both keys and values of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x, y in my_dict.items():
print(x,y)

Department of Electrical and Electronics Engineering


Loop through a dictionary using methods
• There are methods to return the individual keys, values and items of a dictionary.
Ex: The keys() method, return keys of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict.keys():
print(x)
Ex: The values() method, return values of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x in my_dict.values():
print(x)
Ex: The items() method, return both keys and values of a dictionary
my_dict = {'name':'Jack', 'age': 26, ‘address’: ‘Guntur’}
for x, y in my_dict.items():
print(x,y)

Department of Electrical and Electronics Engineering


Adding or changing elements in a dictionary
• New items can be added or can change the value of existing items using
assignment operator.
• If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
Ex:
my_dict = {'name':'Jack', 'age': 26}
my_dict['age'] = 27 #updating
print(my_dict) #{'age':27,'name':'Jack‘}
my_dict['address'] = ‘Guntur' # add item
print(my_dict)
Output:
{'address': 'Downtown', 'age': 27, 'name': 'Jack'}
Ex:
d= dict()
d[1] =12
d[2]= 20
print(d)
Department of Electrical and Electronics Engineering
Built-in functions of a dictionary

Function Description

Return True if all keys of the dictionary are True (or if the
all()
dictionary is empty).

Return True if any key of the dictionary is true. If the dictionary is


any()
empty, return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.

Department of Electrical and Electronics Engineering


Built-in functions of a dictionary

Ex:
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(all(squares))
print(any(squares))
print(len(squares))
print(sorted(squares))

Output:
False
True
6
[0, 1, 3, 5, 7, 9]

Department of Electrical and Electronics Engineering


Dictionary Membership Test

•We can test if a key is in a dictionary or not using the keyword in.
•Membership test is for keys only, not for values.

Ex:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares) # Output: True
print(2 in squares) # Output: False
print(49 in squares) # Output: False

Department of Electrical and Electronics Engineering


Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value


get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist: insert the key, with
setdefault()
the specified value
update() Updates the dictionary with the specified key-value pairs

Department of Electrical and Electronics Engineering


Dictionary Methods

clear():
The clear() method removes all the elements from a dictionary.
Syntax: dictionary.clear()
Parameter Values: No parameters
Ex:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)

Department of Electrical and Electronics Engineering


Dictionary Methods

copy():
The copy() method returns a copy of the specified dictionary.
Syntax: dictionary.copy()
Parameter Values: No parameters
Ex:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x=car.copy()
print(x)

Department of Electrical and Electronics Engineering


Dictionary Methods
fromkeys():
The fromkeys() method returns a dictionary with the specified keys and the
specified value.
Syntax: dictionary.fromkeys(keys, value)
Parameter Values:
Parameter Description
keys Required. An iterable specifying the keys of the new
dictionary
value Optional. The value for all keys. Default value is
Ex: None

x = ('key1', 'key2', 'key3')


y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)

Department of Electrical and Electronics Engineering


Dictionary Methods
get():
The get() method returns the value of the item with the specified key..
Syntax: dictionary.get(keyname, value)
Parameter Values:
Parameter Description
keyname Required. The keyname of the item you want to
return the value from
value Optional. A value to return if the specified key does
not exist. Default value None
Ex: car = { "brand": "Ford", "model": "Mustang", "year": 1964}
x = car.get("model")
print(x)
x = car.get("price", 15000)
print(x)
Department of Electrical and Electronics Engineering
Dictionary Methods
items():
• The items() method returns a view object. The view object contains the
key-value pairs of the dictionary, as tuples in a list.
• The view object will reflect any changes done to the dictionary.
Syntax: dictionary.items()
Parameter Values: No Parameters
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
x = car.items()
print(x)
car["year"] = 2021
print(x)

Department of Electrical and Electronics Engineering


Dictionary Methods
keys():
• The keys() method returns a view object. The view object contains the
keys of the dictionary, as a list.
• The view object will reflect any changes done to the dictionary.
Syntax: dictionary.keys()
Parameter Values: No Parameters
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
x = car.keys()
print(x)
car[“colour"] = “white”
print(x)

Department of Electrical and Electronics Engineering


Dictionary Methods
values():
• The values() method returns a view object. The view object contains the
values of the dictionary, as a list.
• The view object will reflect any changes done to the dictionary.
Syntax: dictionary.values()
Parameter Values: No Parameters
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
x = car.values()
print(x)
car[“year"] = 2021
print(x)

Department of Electrical and Electronics Engineering


Dictionary Methods
pop():
• The pop() method removes the specified item from the dictionary.
• The value of the removed item is the return value of the pop() method.
Syntax: dictionary.pop(keyname, defaultvalue)
Parameter Values: Parameter Description
keyname Required. The keyname of the item you want to remove
defaultvalue Optional. A value to return if the specified key do not exist.
If this parameter is not specified, and the no item with the
specified key is found, an error is raised
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
car.pop(“model”)
print(car)
x = car.pop(“model”)
print(x)
Department of Electrical and Electronics Engineering
Dictionary Methods
popitem():
• The popitem() method removes the item that was last inserted into the
dictionary. In versions before 3.7, the popitem() method removes a
random item.
• The removed item is the return value of the popitem() method, as a tuple.
Syntax: dictionary.popitem()
Parameter Values: No Parameters
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
car.popitem()
print(car)
x = car.popitem()
print(x)

Department of Electrical and Electronics Engineering


Dictionary Methods
setdefault():
• The setdefault() method returns the value of the item with the specified
key.
• If the key does not exist, insert the key, with the specified value.
Syntax: dictionary.setdefault(keyname,
Parameter Description value)
Parameter Values:
keyname Required. The keyname of the item you want to return the
value from
value Optional. If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's value.
Default value None.
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
X=car.setdefault("model", "Bronco")
print(x)
x = car.setdefault("color", "white")
print(x)
Department of Electrical and Electronics Engineering
Dictionary Methods
update():
• The update() method inserts the specified items to the dictionary.
• The specified items can be a dictionary, or an iterable object with key
value pairs.
Syntax: dictionary.update(iterable)
Parameter Values:
Parameter Description
iterable A dictionary or an iterable object with key value pairs, that
will be inserted to the dictionary
Ex:
car = { "brand": "Ford", "model": "Mustang", "year": 1964}
car.update({"color": "White"})
print(car)

Department of Electrical and Electronics Engineering


Python program to read and insert key and values in to a dictionary

Department of Electrical and Electronics Engineering


Python program to read and insert key and values in to a dictionary

d={}
for i in range(3):
k=input("enter key")
v=input("enter value")
d1={k:v}
d.update(d1)
print(d)

Department of Electrical and Electronics Engineering


Python program to concatenate two or more dictionaries

Department of Electrical and Electronics Engineering


Python program to concatenate two or more dictionaries

dict1={1:10, 2:20}
dict2={3:30, 4:40}
dict3={5:50, 6:60}
dict4 = {}
for d in (dict1, dict2, dict3):
dict4.update(d)
print(dict4)

Department of Electrical and Electronics Engineering


Write a Python program to sum all the items in a dictionary

Department of Electrical and Electronics Engineering


Write a Python program to sum all the items in a dictionary

my_dict = {'data1':100, 'data2': -54, 'data3': 247}


print(sum(my_dict.values()))

Department of Electrical and Electronics Engineering


Write a Python Program to Multiply all the items in a dictionary

Department of Electrical and Electronics Engineering


Write a Python Program to Multiply all the items in a dictionary

my_dict = {'data1‘ :100, 'data2': -54, 'data3': 247}


result=1
for key in my_dict:
result=result * my_dict[key]
print(result)

Department of Electrical and Electronics Engineering


Sets
• A set is a collection of data which is both unordered and unindexed.
• In Python Sets are written with curly brackets – { }
Syntax: my_set = {‘hello’,’how’,’are’,’you’}
• Set items are unordered, unchangeable, and do not allow duplicate values.
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
• Unchangeable means that we cannot change the items after the set has been
created but can add new items. Also, a set cannot have mutable items.
• Duplicates Not Allowed (cannot have two items with the same value).
• A set can contain different data types
Ex: set1 = {"abc", 34, True, 45.6}
• From Python's perspective, sets are defined as objects with the data type 'set'
Department of Electrical and Electronics Engineering
Creating a Set

• Creating a set is as simple as placing items inside curly braces


{} separated by comma.
Ex: my_set = {'apple', 'ball‘, 45, True}
my_set = {1, 2, 3}
• Creating empty set: Empty curly braces {} will make an empty dictionary
in Python.To make a set without any elements, use the set() constructor
without any argument.
Ex: my_set = set()
• A set can also be created using set() constructor.
Ex: my_set = set([0, 1, 2, 3, 4])

Department of Electrical and Electronics Engineering


Accessing elements from a Set

• We cannot access or change an element of a set using indexing


or slicing. Set data type does not support it.
• 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..

Ex:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)

Department of Electrical and Electronics Engineering


Adding or changing elements in a set
• Sets are mutable. However, since they are unordered, indexing has no meaning.
• Once a set is created, you cannot change its items, but you can add new items.
• We can add a single element using the add() method, and multiple elements
using the update() method.
• The update() method can take tuples, lists, strings or other sets as its argument. In
all cases, duplicates are avoided.
Ex:
my_set = {1, 3} print(my_set)
my_set.add(2) print(my_set)
my_set.update([2, 3, 4]) print(my_set)
my_set.update([4, 5], {1, 6, 8}) print(my_set)
Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
Department of Electrical and Electronics Engineering
Removing elements from a set
• To remove an item in a set, use the remove(), or the discard() method.
• The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set. On the other hand, the
remove() function will raise an error in such a condition (if element is not present
in the set).
Ex:
my_set = {1, 3, 4, 5, 6} print(my_set)
my_set.discard(4) print(my_set)
my_set.remove(6) print(my_set)
my_set.discard(2) print(my_set)
my_set.remove(2) print(my_set)
Output:
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2

Department of Electrical and Electronics Engineering


Removing elements from a set
• We can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so we will not know
what item will be removed.
• The return value of the pop() method is the removed item.
• We can also remove all the items from a set using the clear() method..
Ex:
my_set = set("HelloWorld")
print(my_set)
print(my_set.pop())
print(my_set.pop())
print(my_set.clear())
Output:
{'H', 'l', 'r', 'W', 'o', 'd', 'e'}
H
{'r', 'W', 'o', 'd', 'e'}
set()
Department of Electrical and Electronics Engineering
Python Set Operations
• Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Set Union
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Union of A and B is a set of all elements from both sets.
• Union is performed using | operator. Same can be accomplished using the
union() method.
Ex: print(A | B)
A.union(B)
B.union(A)
Output: {1, 2, 3, 4, 5, 6, 7, 8}

Department of Electrical and Electronics Engineering


Python Set Operations
• Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Set Intersection
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Intersection of A and B is a set of elements that are common in both the sets.
• Intersection is performed using & operator. Same can be accomplished using the
intersection() method..
Ex: print(A & B)
A. intersection(B)
B. intersection(A)
Output: {4, 5}

Department of Electrical and Electronics Engineering


Python Set Operations
• Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Set Difference
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Difference of the set B from set A, (A - B) is a set of elements that are only in A
but not in B. Similarly, B - A is a set of elements in B but not in A.
• Difference is performed using - operator. Same can be accomplished using the
difference() method.
Ex: print(A - B)
A. difference(B)
print(B - A)
B. difference(A)
Output: {1, 2, 3}
{8, 6, 7}
Department of Electrical and Electronics Engineering
Python Set Operations
• Sets can be used to carry out mathematical set operations like union, intersection,
difference and symmetric difference. We can do this with operators or methods.
Set Symmetric Difference
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Symmetric Difference of A and B is a set of elements in A and B but not in both
(excluding the intersection).
• Symmetric difference is performed using ^ operator. Same can be accomplished
using the method symmetric_difference().
Ex: print(A ^ B)
A. symmetric_difference(B)
B. symmetric_difference(A)
Output: {1, 2, 3, 6, 7 ,8}

Department of Electrical and Electronics Engineering


Other Python Set Methods

Method Description
difference_update() Removes all elements of another set from this set
intersection_update(
Updates the set with the intersection of itself and another
)
symmetric_differenc Updates a set with the symmetric difference of itself and
e_update() another
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

Department of Electrical and Electronics Engineering


Other Python Set Methods
Difference_update()
• The difference_update() updates the set calling difference_update() method with
the difference of sets.
• 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.
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Here, A and B are two sets. difference_update() updates set A with the set
difference of A-B.
Ex: A. difference_update(B)
A Output: {1, 2, 3}
print(A) None
B. difference_update(A)
B {6, 7, 8}
print(B) None

Department of Electrical and Electronics Engineering


Other Python Set Methods
Intersection_update()
• The intersection_update() updates the set calling intersection_update() method
with the intersection of sets.
• The intersection_update() method allows an arbitrary number of arguments
(sets).
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Here, A and B are two sets. intersection_update() updates set A with the elements
which are common in both A and B
Ex: A. intersection_update(B)
A Output: {4, 5}
print(A) None
B. intersection_update(A)
B {4, 5}
print(B) None

Department of Electrical and Electronics Engineering


Other Python Set Methods
Symmetric_Difference_update()
• The symmetric_difference_update() method finds the symmetric difference of
two sets and updates the set calling it.
• The symmetric difference of two sets A and B is the set of elements that are in
either A or B, but not in their intersection.
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Here, A and B are two sets. symmetric_difference_update() updates set A with
the elements that are in A and B but not in both (excluding the intersection).
Ex: A. symmetric_difference_update(B)
A Output: {1, 2, 3, 6, 7, 8}
print(A) None
B. symmetric_difference_update(A)
B {1, 2, 3, 6, 7, 8}
print(B) None

Department of Electrical and Electronics Engineering


Other Python Set Methods
Symmetric_Difference_update()
• The symmetric_difference_update() method finds the symmetric difference of
two sets and updates the set calling it.
• The symmetric difference of two sets A and B is the set of elements that are in
either A or B, but not in their intersection.
• Let us consider the following two sets.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
• Here, A and B are two sets. symmetric_difference_update() updates set A with
the elements that are in A and B but not in both (excluding the intersection).
Ex: A. symmetric_difference_update(B)
A Output: {1, 2, 3, 6, 7, 8}
print(A) None
B. symmetric_difference_update(A)
B {1, 2, 3, 6, 7, 8}
print(B) None

Department of Electrical and Electronics Engineering


Other Python Set Methods
isdisjoint()
• The isdisjoint() method returns True if two sets are disjoint sets. If not, it returns
False.
• Two sets are said to be disjoint sets if they have no common elements.
• Let us consider the following two sets.
A = {1, 2, 3}
B = {6, 7, 8}
• Here, A and B are two sets. isdisjoint() returns True if there are no common
elements in A and B.
Ex: A. isdisjoint(B)
B. isdisjoint(A)

Output: True
True

Department of Electrical and Electronics Engineering


Other Python Set Methods
issubset()
• The issubset() method returns True if all elements of a set are present in another
set (passed as an argument). If not, it returns False.
• Set A is said to be the subset of set B if all elements of A are in B.
• Let us consider the following two sets.
A = {2, 3, 6}
B = {1, 2, 3, 4, 6, 7}
• Here, set A is subset of set B.
Ex: A. issubset(B)
B. issubset(A)

Output: True
False

Department of Electrical and Electronics Engineering


Other Python Set Methods
issuperset()
• The issuperset() method returns True if a set has every elements of another set
(passed as an argument). If not, it returns False.
• Set A is said to be the superset of set B if all elements of B are in A.
• Let us consider the following two sets.
A = {2, 3, 6}
B = {1, 2, 3, 4, 6, 7}
• Here, set B is superset of set A.
Ex: A. issuperset(B)
B. issuperset(A)

Output: False
True

Department of Electrical and Electronics Engineering


Built-in functions of a Set
Function Description
len() Returns the length (the number of items) of the set.
Returns the largest element in an iterable or largest of two or more
max()
items (elements) of a set
Returns the smallest element in an iterable or smallest of two or
min()
more items (elements) of a set
sum() Returns the sum of items of a set.
all() Returns True if all elements of the set are true (or if the set is empty).
Returns True if any element of the set is true. If the set is empty,
any()
returns False.
Returns a new sorted list from elements in the set(does not sort the
sorted()
set itself).
Department of Electrical and Electronics Engineering
Built-in functions of a Set
Ex1:
st_num = {2.5, 3, 6, -5}
print(len(st_num)) print(all(st_num))
print(max(st_num)) print(any(st_num))
print(min(st_num)) print(sorted(st_num))
print(sum(st_num))

Ex2:
ste_strns = {‘a’, ‘b’, ‘c’, ‘d’}
print(len(ste_strns)) print(all(st_num))
print(max(ste_strns)) print(any(st_num))
print(min(ste_strns)) print(sorted(st_num))
#not possible

Department of Electrical and Electronics Engineering


Set Membership Test

•We can test if an item is in a set or not using the keyword in.

Ex:
my_set = set("apple")
print('a' in my_set) # Output: True
print('p' not in my_set) # Output: False

Department of Electrical and Electronics Engineering

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy