Python Comprehension

python comprehension
Photo by Hitesh Choudhary on Unsplash

List Comprehension:

[expression for item in list if (item satisfied this condition)]
# python list is iterable
new_list = []
for i in "impossible":
new_list.append(i)
print(new_list)
['i', 'm', 'p', 'o', 's', 's', 'i', 'b', 'l', 'e']
[i for i in “impossible”]
['i', 'm', 'p', 'o', 's', 's', 'i', 'b', 'l', 'e']
[i for i in range(10) if i%2 !=0]
[1, 3, 5, 7, 9]
[i for i in range(10) if i%2==0 if i%3==0]
[0, 6]

Dictionary Comprehensions:

{key:value for (key, value) in iterable if (condition)}
state = ['Rajasthan', 'UP', 'Bihar']
city = ['Jaipur', 'Kanpur', 'Patna']
output = {}
for (key, value) in zip(state, city):
output[key] = value
print(output)
{'Rajasthan': 'Jaipur', 'UP': 'Kanpur', 'Bihar': 'Patna'}
state = ['Rajasthan', 'UP', 'Bihar']
city = ['Jaipur', 'Kanpur', 'Patna']
{ i:j for (i,j) in zip(state, city)}
{'Rajasthan': 'Jaipur', 'UP': 'Kanpur', 'Bihar': 'Patna'}

Set Comprehensions:

new_list = [1,2,3,4,5,6,7,8]
a = set()
for i in new_list:
a.add(i**3)
print(a)
{64, 1, 512, 8, 343, 216, 27, 125}
new_list = [1,2,3,4,5,6,7,8]
{ i**3 for i in new_list }
{1, 8, 27, 64, 125, 216, 343, 512}

--

--

Software Developer | Machine Learning Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store