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

odds = [x for x in range(10) if x % 2 == 1]
print("Odds          ", odds)

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.

# Import the module collections and be able to access namedtuple
# wihtout having to write collections.namedtuple each time.
from collections import namedtuple
# Create a tuple of class 'Person'
Person = namedtuple("Person", ["name", "age", "gender"])

# Build a list of people by using Person
people = [
    Person("Andy", 30, "m"),
    Person("Ping", 1, "m"), 
    Person("Tina", 32, "f"),
    Person("Abby", 14, "f"),
    Person("Adah", 13, "f"),
    Person("Sebastian", 42, "m"),
    Person("Carol" , 68, "f"),
]

# first, let's show how this namedtuple works.
# Get the first entry in the list (which is Andy from above)
andy = people[0]

# From here, you can access andy like it was a class with attributes
# name, age, and gender (as seeon from the namedtuple)
print("name:  ", andy.name)
print("age:   ", andy.age)
print("gender:", andy.gender)
name:   Andy
age:    30
gender: m

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

male_names = [person.name for person in people if person.gender=="m"]
print("Male names:", male_names)
Male names: ['Andy', 'Ping', 'Sebastian']

Create a list of names where there age

teen_names = [p.name for p in people if 13 <= p.age <= 18 ]
print("Teen names:", teen_names)

Last updated