Python List and Dictionary Comprehension
Python List and Dictionary Comprehension
and
Dictionary
Comprehension
1
List Comprehension
2
A list comprehension generally consist of these parts :
For example :
3
Example: Separate Letters from String
chars=[]
for ch in ‘GKTCS INNOVATIONS’:
chars.append(ch)
print(chars)
4
Example to uses a list comprehension to build a list of squares of the
numbers between 1 and 10.
5
Nested loops
❑ In the example below, any combination of items from two lists in the
form of a tuple is added to a third list object.
6
Applications
One of the applications of list comprehension is to flatten a list comprising
of multiple lists into a single list
7
Nested if conditions with list
comprehension.
8
If..else loop with list comprehension.
9
What is Dictionary Comprehension in
Python?
10
Dictionary comprehensions
11
Dictionary from a list using
comprehension
12
We can use Dictionary comprehensions with if and else statements and with
other expressions too.
13
How to use Dictionary Comprehension..?
Output :
14
Conditionals in Dictionary Comprehension
If Conditional Dictionary Comprehension
Output :
15
Multiple if Conditional Dictionary
Comprehension
print(new_dict)
Output :
{'john': 33}
16
If-else Conditional Dictionary
Comprehension
Output :
{'jack': 'young', 'michael': 'old', 'guido’: 'old', 'john': 'young'}
17
Advantages of Using Dictionary
Comprehension
18
Warnings on Using Dictionary
Comprehension
Even though dictionary comprehensions are great for writing
elegant code that is easy to read, they are not always the right
choice.
❑ They can sometimes make the code run slower and consume
more memory.
19