Write a List in One Line (List Comprehensions)
Source: Dev.to
Introduction
You can build lists in Python with a loop, but list comprehensions let you do the same work in a single, readable line.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The same result with a list comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [n * n for n in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Syntax
Read a comprehension left‑to‑right like a sentence:
[expression for variable in iterable]
- expression – what you want in the new list (calculation, function call, etc.).
- variable – the loop variable (e.g.,
n). - iterable – any iterable object (list, range, string, etc.).
Adding a filter
[expression for variable in iterable if condition]
The if clause keeps only items where condition is True.
Examples
Simple transformations
names = ["alex", "priya", "sam", "jordan"]
upper_names = [name.upper() for name in names]
print(upper_names)
# Output: ['ALEX', 'PRIYA', 'SAM', 'JORDAN']
lengths = [len(name) for name in names]
print(lengths)
# Output: [4, 5, 3, 6]
numbers = range(1, 6)
doubled = [n * 2 for n in numbers]
print(doubled)
# Output: [2, 4, 6, 8, 10]
Filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6, 8, 10]
scores = [45, 92, 78, 61, 34, 88, 55, 97]
passing = [s for s in scores if s >= 60]
print(passing)
# Output: [92, 78, 61, 88, 97]
Transform and filter together
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_evens = [n * n for n in numbers if n % 2 == 0]
print(squared_evens)
# Output: [4, 16, 36, 64, 100]
Working with strings
sentence = "Hello World"
letters = [char for char in sentence if char != " "]
print(letters)
# Output: ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']
words = [" hello ", " world ", " python "]
cleaned = [w.strip() for w in words]
print(cleaned)
# Output: ['hello', 'world', 'python']
Dictionary comprehensions
names = ["Alex", "Priya", "Sam"]
name_lengths = {name: len(name) for name in names}
print(name_lengths)
# Output: {'Alex': 4, 'Priya': 5, 'Sam': 3}
scores = {"Alex": 92, "Priya": 58, "Sam": 75, "Jordan": 44}
passing = {name: score for name, score in scores.items() if score >= 60}
print(passing)
# Output: {'Alex': 92, 'Sam': 75}
When Not to Use a Comprehension
If the logic becomes complex, a regular loop is clearer:
# Hard to read comprehension
result = [process(transform(validate(x))) for x in data if check_one(x) and check_two(x)]
# Clearer as a loop
result = []
for x in data:
if check_one(x) and check_two(x):
validated = validate(x)
transformed = transform(validated)
result.append(process(transformed))
Rule of thumb: use a comprehension only when it can be understood at a glance.
Practice Exercise
Create a file comprehensions_practice.py and, using only comprehensions, perform the following tasks with the given data:
temperatures_c = [0, 10, 20, 30, 40, 100]
words = ["Python", "is", "great", "for", "AI", "and", "ML"]
students = [
{"name": "Alex", "score": 88},
{"name": "Priya", "score": 52},
{"name": "Sam", "score": 76},
{"name": "Jordan", "score": 91},
{"name": "Lisa", "score": 43}
]
- Convert each temperature to Fahrenheit (
F = C * 9/5 + 32) and store the results in a list. - Build a list of words longer than three characters.
- Extract a list of just the student names.
- Extract a list of names of students who passed (score ≥ 60).
- Build a dictionary mapping each student’s name to their score.