Lesson 38 +10 XP

List Comprehension

List Comprehension

List comprehension builds a new list from an existing one in a single, readable line.

The classic example

Old way:

fruits = ["apple", "banana", "cherry"]
newlist = []
for x in fruits:
    if "a" in x:
        newlist.append(x)
print(newlist)  # ['apple', 'banana']

New way:

newlist = [x for x in fruits if "a" in x]
print(newlist)  # ['apple', 'banana']

The syntax

newlist = [expression for item in iterable if condition]
  • expression: what to put in the new list.
  • item: the loop variable.
  • iterable: the collection to loop over.
  • condition (optional): a filter.

Transform as you go

newlist = [x.upper() for x in fruits]
print(newlist)  # ['APPLE', 'BANANA', 'CHERRY']

Filter with condition

newlist = [x for x in fruits if x != "apple"]
print(newlist)  # ['banana', 'cherry']

Use range

squares = [x * x for x in range(6)]
print(squares)  # [0, 1, 4, 9, 16, 25]

Use else in the expression

labels = ["big" if x > 10 else "small" for x in numbers]

TL;DR

  • [expr for item in iterable if cond] builds a list.
  • The condition filters; the expression transforms.
  • It replaces many for-loop-plus-append patterns.