capypad
0 day streak
python / intermediate
Snippet

List Comprehensions with Conditional Logic

List comprehensions provide a concise way to create lists. This intermediate pattern includes an 'if' condition to filter elements while applying a transformation.

snippet.py
python
1
2
3
numbers = [1, 2, 3, 4, 5, 6]
squared_evens = [x**2 for x in numbers if x % 2 == 0]
print(squared_evens) # Output: [4, 16, 36]
Breakdown
1
[x**2 for x in numbers ...]
Iterates through the list and squares each number.
2
... if x % 2 == 0
Only includes numbers where the remainder of division by 2 is zero (even numbers).