Make delicious recipes!

List, Set and Map Comprehensions



Python has some great list comprehension features which allows a programmer to achieve really good functionality is very few lines of code.

# Since python version 3, range() behaves like xrange() and needs list() to avoid lazy evaluation   
>>> nums = range(1,20)
range(1, 20) 

>>> nums = list(range(1,20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]


# First form of list comprehension acts like a filter()
>>> [x for x in nums if x%2 == 0]
[2, 4, 6, 8, 10, 12, 14, 16, 18]


# Second form of list comprehension acts like a map()
>>> [2*x for x in nums]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]


# Third form of list comprehension allows us to mix both the above forms.
>>> [2*x for x in nums if x < 15 and x > 5]
[12, 14, 16, 18, 20, 22, 24, 26, 28]





List Comprehensions can be nested

>>> [i for i in range(3,7)]
[3, 4, 5, 6]

>>> [[j for j in range(2,i)] for i in range(3,7)]
[[2], [2, 3], [2, 3, 4], [2, 3, 4, 5]]


>>> [[[k for k in range(1,j)] for j in range(2,i)] for i in range(3,7)]
[[[1]], [[1], [1, 2]], [[1], [1, 2], [1, 2, 3]], [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]]




Joining two lists
Given two lists:

l1 = [1, 2, 3] and
l2 = ['a', 'b', 'c'],

create a third list
l3 = [1, 'a', 2, 'b', 3, 'c']

Doing this involves a slightly complex use of list comprehensions as follows:

>>> l1 = [1,2,3]
[1, 2, 3]

>>> l2 = ['a','b','c']
['a', 'b', 'c']



>>> l3 = [y for x in zip(l1,l2) for y in x]
[1, 'a', 2, 'b', 3, 'c']


# The above works in the following manner:
>>> tmp = []
>>> for x in zip(l1, l2):
...  for y in x:
...   tmp.append(y)
...

>>> tmp
[1, 'a', 2, 'b', 3, 'c']





Set and map comprehensions are also possible:

>>> setComp = {x for x in [1,2,3,2,1]}
{1, 2, 3}


>>> mapComp = {x: 2*x for x in [1,2,3,4,3,2,1]}
{1: 2, 2: 4, 3: 6, 4: 8}







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal