FANDOM


List comprehension provides a concise way of creating lists.

Generalized Structures Edit

BasicEdit

List ComprehensionEdit
(values) = [(expression) for (value) in (collection)]
For LoopEdit
(values) = []
for (value) in (collection):
    (values).append((expression))

FilteringEdit

List ComprehensionEdit
(values) = [(expression) for (value) in (collection) if (condition)]
For LoopEdit
(values) = []
for (value) in (collection):
    if (condition):
        (values).append((expression))


Examples Edit

Basic ExampleEdit

Here is a piece of code that calculates the squares of 0 - 9 NOT using list comprehension.

squares = []
for x in range(10):
    squares.append(x * x)

Returns : 

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Now here is the same code but using list comprehension:

squares = [x * x for x in range(10)]


FilteringEdit

Here we are calculating the same set of values as above but we are only keeping the even numbers.

even_squares = [x * x for x in range(10) if x % 2 == 0

Returns : 

[0, 4, 16, 36, 64]

If you wanted to do the same thing with a for-loop:

even_squares = []
    for x in range(10):
        if x % 2 == 0:
            even_squares.append(x * x)
Community content is available under CC-BY-SA unless otherwise noted.