Loading lessons...
List Comprehension
List comprehension builds a new list from an existing one in a single, readable line.
The classic example
Old way:
python
fruits = ["apple", "banana", "cherry"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
### ['apple', 'banana']
New way:
python
newlist = [x for x in fruits if "a" in x]
print(newlist)
### ['apple', 'banana']
The syntax
python
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
python
newlist = [x.upper() for x in fruits]
print(newlist)
### ['APPLE', 'BANANA', 'CHERRY']
Filter with condition
python
newlist = [x for x in fruits if x != "apple"]
print(newlist)
### ['banana', 'cherry']
Use range
python
squares = [x * x for x in range(6)]
print(squares)
### [0, 1, 4, 9, 16, 25]
Use else in the expression
python
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.