← Back to Blog
TutorialFebruary 01, 20246 min read
Master Python List Comprehension: From Basics to Advanced
Learn Python list comprehension with practical examples. Transform your code from verbose loops to elegant one-liners.
On this page
What is List Comprehension?
List comprehension is a concise way to create lists by filtering and transforming elements.
Syntax:
[expression for item in iterable if condition]Basic Examples
Square Numbers
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]Filter Even Numbers
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]Convert to Uppercase
words = ["python", "java", "rust"]
upper = [w.upper() for w in words]
# ['PYTHON', 'JAVA', 'RUST']Nested List Comprehension
Flatten a 2D List
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
# [1, 2, 3, 4, 5, 6]Create Cartesian Product
pairs = [(x, y) for x in [1, 2] for y in ['a', 'b']]
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]Performance Benefits
List comprehension is faster than loops:
# Slow (loop)
result = []
for x in range(1000):
if x % 2 == 0:
result.append(x * 2)
# Fast (list comprehension)
result = [x * 2 for x in range(1000) if x % 2 == 0]Dictionary & Set Comprehension
Dict Comprehension
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Set Comprehension
unique = {x % 3 for x in range(10)}
# {0, 1, 2}When is a list comprehension considered best practice?
A list comprehension is considered best practice when you are building a new list by transforming or filtering the items of another iterable, and the whole idea fits comfortably on one line. In that situation it is shorter than the loop, says what it does at a glance, and usually runs a little faster.
Good uses look like this:
prices = [4.5, 12.0, 7.25]
with_tax = [round(p * 1.13, 2) for p in prices]
names = [" ada ", "GRACE", " alan"]
clean = [n.strip().title() for n in names]
print(with_tax)
print(clean)[5.08, 13.56, 8.19]
['Ada', 'Grace', 'Alan']Prefer a regular for loop when:
- You are not keeping the list.
[print(x) for x in items]builds a list ofNonevalues only to throw it away. A loop says what you mean. - Each item needs several steps, a
tryandexcept, orprintcalls along the way. - It no longer reads easily. More than one
ifor more than twoforclauses is a sign to switch to a loop. - You only need one result, such as a total. Use a generator expression without the square brackets, which does not build a list at all:
numbers = [3, 4, 5]
print(sum(n * n for n in numbers))
print(any(n > 4 for n in numbers))50
TrueA useful test: if you have to read it twice, write the loop.
Best Practices
- Keep it simple: One condition max, consider readability
- Use meaningful names:
[s.strip() for s in lines]not[x for x in y] - For complex logic: Use regular loops, don't force comprehension
By PythonExecutor Team