Python: Generate List (List Comprehension)

By Xah Lee. Date: . Last updated: .

2 major ways to generate a list.

List Comprehension

List Comprehension is a special syntax for building a list, or a nested list. You can use for, while, 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.

# generate a list
xx = [i + 1 for i in [1, 2, 3]]
print(xx == [2, 3, 4])

Build a list of tuples:

# build a list of tuples
xx = [(i, i * 2) for i in range(1, 5)]
print(xx == [(1, 2), (2, 4), (3, 6), (4, 8)])

The iteration part can be nested.

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

print(
    xx
    == [
        (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),
    ]
)

Python Data Structure