Introduction
List comprehensions are one of Python’s most elegant features. They allow you to create new lists in a single line of code, replacing longer for-loops with concise expressions. In this article, you’ll learn how to use list comprehensions effectively, including conditions and nested loops.
Basic Syntax
Here’s the general format:
[expression for item in iterable]
Example:
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
With Conditions
You can add a condition at the end to filter elements:
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
Using if-else Inside
Include a conditional expression inside the comprehension:
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels) # ['even', 'odd', 'even', 'odd', 'even']
Nested Loops
You can include multiple for-clauses to create combinations:
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs) # [(1, 3), (1, 4), (2, 3), (2, 4)]
List Comprehension vs For Loop
Traditional loop:
result = []
for x in range(5):
result.append(x * 2)
List comprehension:
result = [x * 2 for x in range(5)]
They produce the same result, but the latter is shorter and easier to read.
Conclusion
List comprehensions help you write Pythonic code that’s both concise and efficient. Once you’re comfortable with their syntax and structure, they can replace many loops in your daily work—just be mindful of readability when things get too complex.
Comment