Python: List Comprehension

By Xah Lee. Date: . Last updated: .

List Comprehension is a special syntax for building list, or nested lists. You can use “for loops” to do exactly the same, but List Comprehension makes the code shorter.

List comprehension syntax has the form

[expression for var in list]

where expression is evaluated with var replaced by each element in list.

# -*- coding: utf-8 -*-
# python

# generate a list, using list comprehension syntax

li = [ i+1 for i in [1,2,3] ]
print li                        # prints [2, 3, 4]

Following example build a list of tuples.

# -*- coding: utf-8 -*-
# python

# generate a list of tuples

li = [ (i,i*2) for i in range(1,6)]
print li      # prints [(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]

The iteration part can be nested. Example:

# -*- coding: utf-8 -*-
# python

myList = [ (i,j) for i in range(1,6) for j in range(1,4) ]
print myList

# output
# [
#  (1, 1), (1, 2), (1, 3),
#  (2, 1), (2, 2), (2, 3),
#  (3, 1), (3, 2), (3, 3),
#  (4, 1), (4, 2), (4, 3),
#  (5, 1), (5, 2), (5, 3)
# ]

5. Data Structures — Python v2.7.6 documentation#list-comprehensions

Ask me question on patreon