List Comprehensions Advanced
Advanced List Comprehensions
List comprehensions can be more powerful than basic examples. You can use multiple conditions, nested loops, and complex expressions. Advanced comprehensions help write concise, readable code for complex data transformations.
Mastering advanced comprehensions makes you a more Pythonic programmer and helps you write efficient code.
Multiple Conditions
You can use multiple if conditions in a comprehension:
multiple_conditions.py
# Multiple conditions
numbers = [x for x in range(20) if x % 2 == 0 if x > 5]
print(numbers) # [6, 8, 10, 12, 14, 16, 18]
# Using and/or in conditions
result = [x for x in range(10) if x % 2 == 0 and x > 2]
print(result) # [4, 6, 8]
# Complex filtering
words = ["hello", "world", "python", "code"]
long_vowels = [w for w in words if len(w) > 4 if "o" in w]
print(long_vowels) # ['hello', 'world']
Nested Comprehensions
You can nest comprehensions for complex data structures:
nested_advanced.py
# Matrix operations
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Flatten with condition
nested = [[1, 2, 3], [4, 5], [6, 7, 8]]
evens = [num for sublist in nested for num in sublist if num % 2 == 0]
print(evens) # [2, 4, 6, 8]
# Cartesian product
colors = ["red", "blue"]
sizes = ["S", "M", "L"]
combinations = [(color, size) for color in colors for size in sizes]
print(combinations)
Dictionary and Set Comprehensions
Python also supports dictionary and set comprehensions:
dict_set_comprehensions.py
# Dictionary comprehension
squares = {x: x ** 2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Dictionary comprehension with condition
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(unique_lengths) # {5, 6}
# Transform dictionary
original = {"a": 1, "b": 2, "c": 3}
doubled = {k: v * 2 for k, v in original.items()}
print(doubled) # {'a': 2, 'b': 4, 'c': 6}
Best Practices
✅ Advanced Comprehension Tips
• Keep comprehensions readable - don't make them too complex
• Use comprehensions for simple transformations
• Consider using loops for complex logic
• Dictionary and set comprehensions are powerful tools
• Test comprehensions with simple examples first
main.py
📤 Output
Click "Run" to execute...