Python List Comprehension
List comprehension is Python’s syntax to concisely create lists. The general syntax allows creating a new list by evaluating an expression on each element within the iterable and possibly further restricting the elements based on certain conditions.
Basic Syntax:
new_list = [expression for item in iterable if condition]
expression
: the transformation or operation to be carried out on each element.item
: The iteration variable representing each element in theiterable
.iterable
: the sequence of items being processed; e.g., a list, range, etc.Condition
: An optional filter that specifies whether an item should be included.
Examples:
1. Create a List from a Range:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- Explanation: For each
x
in the range from 0 to 9, calculatex**2
and add it to the list.
2. Filter Items:
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
- Explanation: Include only numbers that are divisible by 2.
3. Transform and Filter:
odd_squares = [x**2 for x in range(10) if x % 2 != 0]
print(odd_squares) # Output: [1, 9, 25, 49, 81]
- Explanation: Square only the odd numbers in the range.
4. Nested Loops:
pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs) # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
- Explanation: Combine every
x
inrange(3)
with everyy
inrange(3)
.
5. Flatten a Nested List:
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
- Explanation: Loop through each
row
in the matrix, then loop through eachnum
in the row.
6. List Comprehension with Functions:
def square(x):
return x**2
results = [square(x) for x in range(5)]
print(results) # Output: [0, 1, 4, 9, 16]
- Explanation: Apply the
square
function to each number in the range.
Comparison with a For Loop:
Using list comprehension is often more concise than a traditional for
loop.
Using a For Loop:
squares = []
for x in range(10):
squares.append(x**2)
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Using List Comprehension:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Advanced Usage:
1. Conditional Expression in expression
:
results = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(results) # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']
Explanation: Include conditional logic directly in the expression
.
2. Set and Dictionary Comprehension:
- Set Comprehension:
unique_squares = {x**2 for x in range(5)}
print(unique_squares) # Output: {0, 1, 4, 9, 16}
- Dictionary Comprehension:
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Advantages of List Comprehension:
- Conciseness: The code is shorter and more readable.
- Performance: Usually, it runs faster than the equivalent
for
loops, due to Python’s specific implementation. - Readability: Clear intent to generate or transform lists.
When Not to Use:
- If the logic is too complex, a traditional loop with comments might be more readable.
- Avoid using list comprehensions for side effects (such as printing or modifying external variables).