In-built Data Structures in python
Python Programming
Prof. Smita S. Mande
Smita.mande2@vit.edu
Department of Computer Engineering
BRACT’S, Vishwakarma Institute of Technology, Pune
(An Autonomous Institute affiliated to Savitribai Phule Pune University)
(NBA and NAAC accredited, ISO 9001:2015 certified)
Set
• A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
• Python’s set class represents the mathematical notion of a set.
• The major advantage of using a set, as opposed to a list, is that it has a highly optimized method
for checking whether a specific element is contained in the set.
• This is based on a data structure known as a hash table.
• Since sets are unordered, we cannot access items using indexes like we do in lists.
• Sets are written with curly brackets { } .
Department of Engineering Sciences and Humanities, VIT, Pune
Creating Python Sets
• A set is created by placing all the items (elements) inside curly braces { }, separated
by comma, or by using the built-in set( ) function.
• It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or
dictionaries as its elements.
# set of integers
my_set = {1, 2, 3} Output
print(my_set)
{1, 2, 3}
# set of mixed datatypes {1.0, (1, 2, 3),
my_set = {1.0, "Hello", (1, 2, 3)} 'Hello'}
print(my_set)
Department of Engineering Sciences and Humanities, VIT, Pune
# set cannot have duplicates
my_set = {1, 2, 3, 4, 3, 2} Output
print(my_set)
{1, 2, 3, 4}
# we can make set from a list {1, 2, 3}
my_set = set([1, 2, 3, 2]) Traceback (most recent call last):
print(my_set) File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
# set cannot have mutable items here TypeError: unhashable type: 'list'
[3, 4] is a mutable list this will cause an
error.
my_set = {1, 2, [3, 4]}
Department of Engineering Sciences and Humanities, VIT, Pune
Creating an empty set is a bit tricky.
Empty curly braces { } will make an empty dictionary in Python. To
make a set without any elements, we use the set( ) function without
any argument.
# Distinguish set and dictionary while creating empty set
# initialize a with { }
a={}
# check data type of a
print(type(a)) Output
# initialize a with set( )
a = set( ) <class 'dict'>
# check data type of a <class 'set'>
print(type(a))
Department of Engineering Sciences and Humanities, VIT, Pune
Frozen set
• Frozen sets are immutable objects that only support methods and operators that produce a result
without affecting the frozen set. While elements of a set can be modified at any time, elements of
the frozen set remain the same after creation.
# Python program to demonstrate differences between normal and frozen set
normal_set = set({"a", "b","c“})
print("Normal Set")
print(normal_set)
Output:
# A frozen set
Normal Set
frozen_set = frozenset({"e", "f", "g“}) {'a', 'b', 'c'}
print("\nFrozen Set") Frozen Set
print(frozen_set) frozenset({'f', 'g', 'e'})
# Uncommenting below line would cause error as we are trying to add element
to a frozen set
# frozen_set.add("h")
Department of Engineering Sciences and Humanities, VIT, Pune
Adding items to the set
• Python provides the add( ) method and update( ) method which can be
used to add some particular item to the set.
1. The add( ) method is used to add a single element
2. The update( ) method is used to add multiple elements to the set. It
accepts iterable as an argument.
Department of Engineering Sciences and Humanities, VIT, Pune
Example: 1 - Using add( ) method
Months = {"January","February", "March", "April", "May", "June“} OUTPUT
printing the original set ...
{'May', 'June', 'March', 'January', 'February', 'April’}
print("\nprinting the original set ... ")
print(Months) Adding other months to the set...
Printing the modified set...
print("\nAdding other months to the set...") {'May', 'July', 'June', 'August', 'March', 'January', 'February',
Months.add("July") 'April’}
Months.add ("August")
looping through the set elements ...
print("\nPrinting the modified set...")
May
print(Months) July
June
print("\nlooping through the set elements ... ") August
for i in Months: March
print(i) January
February
April
Department of Engineering Sciences and Humanities, VIT, Pune
Example - 2 Using update( ) function
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"])
print("\nprinting the modified set ... ")
print(Months)
printing the original set ...
{'February', 'March', 'June', 'April', 'January', 'May'}
updating the original set ...
printing the modified set ...
{'February', 'March', 'June', 'April', 'July', 'September', 'January', 'October', 'August', 'May'}
Department of Engineering Sciences and Humanities, VIT, Pune
Removing items from the set
• Python provides the discard( ) method and remove( ) method which
can be used to remove the items from the set.
• The difference between these function, using discard( ) function if the
item does not exist in the set then the set remain unchanged whereas
remove( ) method will throw an error.
Department of Engineering Sciences and Humanities, VIT, Pune
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months) printing the original set ...
{'April', 'May', 'March', 'June', 'January',
print("\nRemoving some months from the set...") 'February'}
months.discard("January")
months.discard("May") Removing some months from the set...
print("\nPrinting the modified set...") Printing the modified set...
print(months) {'April', 'March', 'June', 'February'}
print("\nlooping through the set elements ... ") looping through the set elements ...
for i in months: April
print(i) March
June
February
Department of Engineering Sciences and Humanities, VIT, Pune
Example-2 Using remove( ) function
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...")
months.remove("January")
months.remove("May")
print("\nPrinting the modified set...")
print(months)
Output:
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
Removing some months from the set...
Printing the modified set...
{'February', 'June', 'April', 'March'}
Department of Engineering Sciences and Humanities, VIT, Pune
We can also use the pop( ) method to remove the item. Generally, the pop( ) method will always
remove the last item but the set is unordered, we can't determine which element will be popped
from set.
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nRemoving some months from the set...")
Months.pop( )
Months.pop( )
print("\nPrinting the modified set...") Output:
print(Months) printing the original set ...
{'June', 'January', 'May', 'April', 'February',
In the above code, the last element of the 'March'}
Month set is March but the pop( ) method
removed the June and January because the Removing some months from the set...
set is unordered and the pop( ) method could
not determine the last element of the set. Printing the modified set...
{'May', 'April', 'February', 'March'}
Department of Engineering Sciences and Humanities, VIT, Pune
Python Set Operations
Input :
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
Output :
Union : {0, 1, 2, 3, 4, 5, 6, 8}
Intersection : {2, 4}
Difference : {0,6,8}
Symmetric difference : {0, 1, 3, 5, 6, 8}
Department of Engineering Sciences and Humanities, VIT, Pune
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
# union
print("Union :", A | B) Output:
Union : {0, 1, 2, 3, 4, 5, 6, 8}
# intersection Intersection : {2, 4}
print("Intersection :", A & B) Difference : {0, 8, 6}
Symmetric difference : {0, 1, 3, 5, 6, 8}
# difference
print("Difference :", A - B)
# symmetric difference
print("Symmetric difference :", A ^ B)
Department of Engineering Sciences and Humanities, VIT, Pune
Set Membership Test
We can test if an item exists in a set or not, using the in keyword.
my_set = set("apple")
Print(my_set) Output
# check if 'a' is present
print('a' in my_set) {'e', 'p', 'l', 'a'}
True
# check if 'p' is present False
print('p' not in my_set)
Department of Engineering Sciences and Humanities, VIT, Pune
Set methods in python
Function Description
copy( ) Returns a shallow copy of a set
union( ) Returns the union of sets in a new 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
intersection( ) Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and 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
symmetric_difference( ) Returns the symmetric difference of two sets as a new set
symmetric_difference_update( ) Updates a set with the symmetric difference of itself and another
Department of Engineering Sciences and Humanities, VIT, Pune
The copy( ) method copies the set.
Syntax
set.copy( )
fruits = {"apple", "banana",
"cherry"}
x = fruits.copy() {'apple', 'banana', 'cherry'}
print(x)
Department of Engineering Sciences and Humanities, VIT, Pune
The difference( ) method returns a set that contains the x = {"apple", "banana", "cherry"}
difference between two sets. y = {"google", "microsoft", "apple"}
Meaning: The returned set contains items that exist z = x.difference(y)
only in the first set, and not in both sets.
print(z)
Syntax
set.difference(set)
{'banana', 'cherry'}
Department of Engineering Sciences and Humanities, VIT, Pune
The intersection() method returns a set that contains the
Example
similarity between two or more sets.
Compare 3 sets, and return a set
with items that is present in all 3
Meaning: The returned set contains only items that exist in both sets:
sets, or in all sets if the comparison is done with more than two
sets. x = {"a", "b", "c"}
y = {"c", "d", "e"}
Syntax z = {"f", "g", "c"}
set.intersection(set1, set2 ... etc)
result = x.intersection(y, z)
Parameter Values
print(result)
Set1: Required. The set to search for equal items in
Set2: Optional. The other set to search for equal items in.
You can compare as many sets you like. Separate the sets with a {‘c’}
comma
Department of Engineering Sciences and Humanities, VIT, Pune
The isdisjoint() method returns True if none of the items are present in both
sets, otherwise it returns False.
Syntax
set.isdisjoint(set)
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
False
z = x.isdisjoint(y)
print(z)
Department of Engineering Sciences and Humanities, VIT, Pune
The issubset() method returns True if all items in the set exists in the
specified set, otherwise it returns False.
Syntax
set.issubset(set)
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
False
z = x.issubset(y)
print(z)
Department of Engineering Sciences and Humanities, VIT, Pune
The issuperset() method returns True if all items in the specified set exists in the
original set, otherwise it returns False.
Syntax
set.issuperset(set)
Return True if all items set y are present in set x:
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"} True
z = x.issuperset(y)
print(z)
Department of Engineering Sciences and Humanities, VIT, Pune
The difference_update( ) method removes the items that exist in both sets.
The difference_update( ) method is different from the difference( ) method, because the
difference( ) method returns a new set, without the unwanted items, and the
difference_update( ) method removes the unwanted items from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.difference_update(y) {'banana', 'cherry'}
print(x)
Department of Engineering Sciences and Humanities, VIT, Pune
The intersection_update( ) method is different from the intersection( ) method, because the
intersection( ) method returns a new set, without the unwanted items, and the
intersection_update( ) method removes the unwanted items from the original set.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y) {'apple'}
print(x)
Department of Engineering Sciences and Humanities, VIT, Pune
The symmetric_difference_update( ) method updates the original set by removing items
that are present in both sets, and inserting the other items.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
{'google', 'banana', 'cherry', 'microsoft'}
x.symmetric_difference_update(y)
print(x)
Department of Engineering Sciences and Humanities, VIT, Pune
Dictionary
• Python dictionary is an unordered collection of items. Each item of a dictionary has a key:
value pair.
• Creating a dictionary is as simple as placing items inside curly braces {} separated by
commas.
• An item has a key and a corresponding value that is expressed as a pair (key: value).
• While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
Department of Engineering Sciences and Humanities, VIT, Pune
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
OUTPUT:
{1: 'apple', 2: 'ball'}
# dictionary with mixed keys {'name': 'John', 1: [2, 4, 3]}
my_dict = {'name': 'John', 1: [2, 4, 3]} {1: 'apple', 2: 'ball'}
# using dict( )
my_dict = dict({1:'apple', 2:'ball'})
Department of Engineering Sciences and Humanities, VIT, Pune
Accessing the dictionary values
• The values can be accessed in the dictionary by using the keys as
keys are unique in the dictionary.
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"} OUTPUT:
printing Employee data ....
print("printing Employee data .... ") Name : John
print("Name : %s" %Employee["Name"]) Age : 29
print("Age : %d" %Employee["Age"]) Salary : 25000
Company : GOOGLE
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Department of Engineering Sciences and Humanities, VIT, Pune
There is also a method called get( ) that will also help in accessing
the element from a dictionary.
# Creating a Dictionary
Dict = {1: ‘learn', 'name': ‘for', 3: ‘fun'} OUTPUT:
Accessing a element using get:
# accessing a element using get( ) fun
print("Accessing a element using get:")
print(Dict.get(3))
Department of Engineering Sciences and Humanities, VIT, Pune
Adding elements to a Dictionary
• The dictionary is a mutable data type, and its values can be updated by
using the specific keys.
• The value can be updated along with key Dict[key] = value.
• The update( ) method is used to update an existing value
• Note: If the key-value already present in the dictionary, the value gets
updated. Otherwise, the new keys gets added in the dictionary.
Department of Engineering Sciences and Humanities, VIT, Pune
# Creating an empty Dictionary
Dict = { }
print("Empty Dictionary: ")
print(Dict) Empty Dictionary:
# Adding elements to dictionary one at a time {}
Dict[0] = 'Peter'
Dictionary after adding 3 elements:
Dict[2] = 'Joseph' {0: 'Peter', 2: 'Joseph', 3: 'Rocky'}
Dict[3] = ‘Rocky'
print("\nDictionary after adding 3 elements: ") Dictionary after adding 3 elements:
print(Dict) {0: 'Peter', 2: 'Joseph', 3: 'Rocky', 'Emp_ages': (20, 33, 24)}
# Adding set of values with a single Key Updated key value:
Dict['Emp_ages'] = 20, 33, 24 {0: 'Peter', 2: 'Joseph', 3: 'Python', 'Emp_ages': (20, 33, 24)}
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = ‘Python'
print("\nUpdated key value: ")
print(Dict)
Department of Engineering Sciences and Humanities, VIT, Pune
Deleting elements using del keyword
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print("printing Employee data .... ") printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company':
print(Employee) 'GOOGLE’}
print("Deleting some of the employee data")
del Employee["Name"] Deleting some of the employee data
del Employee["Company"]
printing the modified information
print("printing the modified information ") {'Age': 29, 'salary': 25000}
print(Employee) Deleting the dictionary: Employee
print("Deleting the dictionary: Employee")
Lets try to print it again
del Employee Traceback (most recent call last):
print("Lets try to print it again ") File "C:/Users/Samrat Mande/pythonProject/J
print(Employee) div/membershipop.py", line 15, in <module>
print(Employee)
NameError: name 'Employee' is not defined
Department of Engineering Sciences and Humanities, VIT, Pune
Using pop( ) method
The pop( ) method accepts the key as an argument and remove the associated value
Python also provides a built-in methods popitem( ) and clear( ) method for removing elements from
the dictionary. 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, whereas the clear( ) method
removes all elements from the dictionary.
# Creating a Dictionary
Dict = {1: ‘Python', 2: ‘Program', 3: ‘Lab'}
OUTPUT:
# Deleting a key using pop( ) method
pop_ele = Dict.pop(3) {1: 'Python', 2: 'Program'}
print(Dict)
Department of Engineering Sciences and Humanities, VIT, Pune
Dictionary methods in python
1. pop( ) :- Returns and removes the element with the given key.
2. len( ) :- It returns the count of key entities of the dictionary elements.
3. copy( ) :- This function creates the shallow copy of the dictionary into other dictionary.
4. fromkeys(seq,value) :- This method is used to declare a new dictionary from the sequence
mentioned in its arguments.
5. has_key( ) :- This function returns true if specified key is present in the dictionary, else returns
false.
6. get(key, def_val) :- This function return the value associated with the key mentioned in
arguments. If key is not present, the default value is returned.
7. setdefault(key, def_value) :- This function also searches for a key and displays its value like
get( ) but, it creates new key with def_value if key is not present.
Department of Engineering Sciences and Humanities, VIT, Pune
dic = {1:'VIT', 2:'WELCOME', 3:'MORNING'}
print('original: ', dic)
# Accessing value for key original: {1: 'VIT', 2: 'WELCOME', 3: 'MORNING'}
print(dic.get(1)) VIT
dict_keys([1, 2, 3])
# Accessing keys for the dictionary dict_values(['VIT', 'WELCOME', 'MORNING'])
print(dic.keys()) dict_items([(1, 'VIT'), (2, 'WELCOME'), (3,
'MORNING')])
# Accessing keys for the dictionary
print(dic.values())
# Printing all the items of the Dictionary
print(dic.items())
Department of Engineering Sciences and Humanities, VIT, Pune
fromkeys(seq,value) :- This method is used to declare a new dictionary from the sequence
mentioned in its arguments.
You can optionally set a value for all the keys, but by default the value for the keys will be
None.
#create sequence of strings
cities = ('Paris','Athens', 'Madrid') cities = ('Paris','Athens', 'Madrid')
continent = 'Europe'
my_dictionary = dict.fromkeys(cities) my_dictionary = dict.fromkeys(cities,continent)
print(my_dictionary)
print(my_dictionary)
{'Paris': 'Europe', 'Athens': 'Europe', 'Madrid':
{'Paris': None, 'Athens': None, 'Madrid': None} 'Europe'}
Department of Engineering Sciences and Humanities, VIT, Pune
setdefault(keyname, def_value) :-
This function also searches for a key and displays its value like get( ) but, it creates new key
with def_value if key is not present.
dictionary.setdefault(keyname, def_value)
Keyname: Required. The keyname of the item you want to return the value from
Def_value: Optional.
car = {
"brand": "Ford",
White
"model": "Mustang",
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
"year": 1964
'White'}
}
x = car.setdefault("color", "White")
print(x)
print(car)
Department of Engineering Sciences and Humanities, VIT, Pune
List of Mutable and Immutable objects
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’
is the ability of objects to change their values.
Immutable is the when no change is possible over time. In Python, if the value of an object
cannot be changed over time, then it is known as immutable.
Mutable Objects Immutable Objects
Lists Numbers (Integer, Rational, Float,
Decimal, Complex & Booleans)
Sets
Strings
Dictionaries Tuples
Frozen Sets
Department of Engineering Sciences and Humanities, VIT, Pune
Data Type Conversion
• Python defines type conversion functions to directly convert one data type
to another which is useful in day to day and competitive programming.
• There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Department of Engineering Sciences and Humanities, VIT, Pune
Implicit Type Conversion
• In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement
x = 10
print("x is of type:",type(x))
Output:
y = 10.6
print("y is of type:",type(y)) x is of type: <class 'int'>
y is of type: <class 'float'>
x=x+y 20.6
print(x) x is of type: <class 'float'>
print("x is of type:",type(x))
Department of Engineering Sciences and Humanities, VIT, Pune
Explicit Type Conversion
In Explicit Type Conversion, the data type is manually changed by the user as per their
requirement.
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base
in which string is if the data type is a string.
2. float( ): This function is used to convert any data type to a floating-point number
3. ord( ) : This function is used to convert a character to integer.
4. hex( ) : This function is to convert integer to hexadecimal string.
5. oct( ) : This function is to convert integer to octal string.
6. tuple( ) : This function is used to convert to a tuple.
Department of Engineering Sciences and Humanities, VIT, Pune
Explicit Type Conversion
7. set( ) : This function returns the type after converting to set.
8. list( ) : This function is used to convert any data type to a list type.
9. dict( ) : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str( ) : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.
12. chr(number) : This function converts number to its corresponding ASCII character.
Department of Engineering Sciences and Humanities, VIT, Pune
# Python code to demonstrate Type conversion using int( ), float( )
# initializing string
s = "10010"
#printing string converting with base 2 to int
c = int(s,2) Output:
print ("After converting to integer base 2 : ", end="")
print (c) After converting to integer base 2 : 18
After converting to float : 10010.0
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
Department of Engineering Sciences and Humanities, VIT, Pune
# Python code to demonstrate Type conversion using ord( ), hex( ), oct( )
s = ' A'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
# printing integer converting to hexadecimal string Output:
c = hex(56) After converting character to integer : 65
print ("After converting 56 to hexadecimal string : ",end="") After converting 56 to hexadecimal string : 0x38
print (c) After converting 56 to octal string : 0o70
# printing integer converting to octal string
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)
Department of Engineering Sciences and Humanities, VIT, Pune
# Python code to demonstrate Type conversion using tuple ( ), set( ), list( )
# initializing string
s = ‘python'
# printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)
After converting string to tuple : ('p', 'y', 't', 'h', 'o', 'n')
# printing string converting to set After converting string to set : {'o', 'p', 't', 'y', 'h', 'n'}
c = set(s) After converting string to list : ['p', 'y', 't', 'h', 'o', 'n']
print ("After converting string to set : ",end="")
print (c)
# printing string converting to list
c = list(s)
print ("After converting string to list : ",end="")
print (c)
Department of Engineering Sciences and Humanities, VIT, Pune
# Python code to demonstrate Type conversion using dict( ), complex( ), str( )
# initializing integers
a=1
b=2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3)) Output:
# printing integer converting to complex number
c = complex(1,2) After converting integer to complex number : (1+2j)
print ("After converting integer to complex number : ",end="") After converting integer to string : 1
print (c) After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
# printing integer converting to string
c = str(a)
print ("After converting integer to string : ",end="")
print (c)
# printing tuple converting to expression dictionary
c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)
Department of Engineering Sciences and Humanities, VIT, Pune
# Python code to demonstrate Type conversion using chr( )
# Convert ASCII value to characters
a = chr(76) Output:
b = chr(77)
L
print(a) M
print(b)
Department of Engineering Sciences and Humanities, VIT, Pune
Comprehensions in python
• Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined.
• Python supports the following 4 types of comprehensions:
1. List Comprehensions
2. Dictionary Comprehensions
3. Set Comprehensions
4. Generator Comprehensions
Department of Engineering Sciences and Humanities, VIT, Pune
List Comprehension
• List comprehension is an elegant way to define and create lists based on existing lists.
newlist = [expression for item in iterable if condition == True]
• Return value: It is a new list, leaving the old list unchanged.
• Condition: The condition is a filter that only accepts the items that evaluate to True.
• Iterable: The iterable can be any iterable object like a list, set,strings etc.
• List comprehension may or may not contain an if condition.
• List comprehensions can contain multiple for (nested list comprehensions).
Department of Engineering Sciences and Humanities, VIT, Pune
Example 1: Suppose we want to create an output list which contains only the
even numbers which are present in the input list.
input_list = [1,2,3,4,4,5,6,7,8,15,24,88,57,23,90]
output_list = [ ]
# Using loop for constructing output list
for i in input_list:
if i % 2 == 0: Output List using for loop: [2, 4, 4, 6, 8, 24, 88, 90]
output_list.append(i)
print("Output List using for loop:", output_list)
Department of Engineering Sciences and Humanities, VIT, Pune
Example 1: Suppose we want to create an output list which contains only the even numbers
which are present in the input list.
input_list = [1,2,3,4,4,5,6,7,8,15,24,88,57,23,90]
list_using_comp = [i for i in input_list if i % 2 == 0]
print("Output List using list comprehensions:",list_using_comp)
Output List using list comprehensions: [2, 4, 4, 6, 8, 24, 88, 90]
Department of Engineering Sciences and Humanities, VIT, Pune
Example 2: Suppose we want to create an output list which contains squares of all the numbers
from 1 to 9
output_list = [ ]
for i in range(1, 10):
output_list.append(i ** 2)
print("Output List using for loop:", output_list)
Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]
list_using_comp = [i**2 for i in range(1, 10)]
print("Output List using list comprehension:", list_using_comp)
Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Department of Engineering Sciences and Humanities, VIT, Pune
Set Comprehension
• Set comprehensions are pretty similar to list comprehensions.
• The only difference between them is that set comprehensions use curly brackets { }
Example 1 : Suppose we want to create an output set which contains only the even
numbers that are present in the input list. Note that set will discard all the duplicate
values
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set( )
Output Set using for loop: {2, 4, 6}
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)
Department of Engineering Sciences and Humanities, VIT, Pune
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp = {var for var in input_list if var % 2 == 0}
print("Output Set using set comprehensions:",set_using_comp)
Output:
Output Set using set comprehensions: {2, 4, 6}
Department of Engineering Sciences and Humanities, VIT, Pune
Dictionary Comprehension
• Extending the idea of list comprehensions, we can also create a
dictionary using dictionary comprehensions.
output_dict = {key:value for (key, value) in iterable
if (key, value satisfy this condition)}
Department of Engineering Sciences and Humanities, VIT, Pune
Example 1: Suppose we want to create an output dictionary which contains only the odd numbers that are present in
the input list as keys and their cubes as values
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = { }
# Using loop for constructing output dictionary
for var in input_list:
if var % 2 != 0:
output_dict[var] = var**3
print("Output Dictionary using for loop:", output_dict )
Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
input_list = [1,2,3,4,5,6,7]
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
print("Output Dictionary using dictionary comprehensions:", dict_using_comp)
Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7: 343}
Department of Engineering Sciences and Humanities, VIT, Pune