List Comprehensions

One of Python's most "Pythonic" features is the list comprehension. It's a way of creating a list in a compact and, once you get used to them, readable way. See the demonstrations below.

The preferred 'pythonic' way to create a list

numbers_0_to_9 = [x for x in range(10)]
print("Numbers 0 to 9", numbers_0_to_9)
Numbers 0 to 9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The above is equivalent to the following just more compact:

numbers_0_to_9 = []
for x in range(10):
    numbers_0_to_9.append(x)
print("Numbers 0 to 9", numbers_0_to_9)
Numbers 0 to 9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can also choose to do computation / flow control when generating lists

squares = [x * x for x in range(10)]
print("Squares       ", squares)
Squares        [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

This example uses the "modulo" operator

Advanced List Comprehensions [optional]

If you're already an advanced programmer, you may be interested in some of these more advanced list comprehensions. They're one of the things that experienced Python users learn to love about Python.

This example also uses a data type called a namedtuple which is similar to a struct data type in other languages.

now let's show what we can do with a list comprehension

Create a list of names where there age

Last updated

Was this helpful?