python list comprehension
Python list comprehension is pretty useful at times to make code easier to read. There are typically 2 pattern for using list comprehension.
Pattern 1 (filtering)
[expression for item in iterable if condition]
Example:
nums = [1, 2, 3, 4, 5]
evens = [n for n in nums if n % 2 == 0]
print(evens) # [2, 4]
A filtering
# filtering
[x for x in items if x > 0] filter → include only x > 0
In filtering we can chain multiple condition
nums = range(10)
filtered = [n for n in nums if n % 2 == 0 if n > 3]
print(filtered) # [4, 6, 8]
Pattern 2 (transform)
[expression_if_true if condition else expression_if_false for item in iterable]
nums = [1, 2, 3, 4]
labels = ["even" if n % 2 == 0 else "odd" for n in nums]
print(labels) # ['odd', 'even', 'odd', 'even']
A transformation construct
[x if x > 0 else 0 for x in items] transform → replace negatives with 0
And here is an example to illustrate this
nums = [-2, -1, 0, 1, 2]
print([x for x in nums if x > 0]) # [1, 2]
print([x if x > 0 else 0 for x in nums]) # [0, 0, 0, 1, 2]
Pattern 3 - combining filter and transformation together
We can combine filter and tranformation with "if" filter at the end, for example
nums = [1, 2, 3, 4, 5, 6]
result = [n**2 if n % 2 == 0 else 0 for n in nums if n > 2]
print(result) # [0, 16, 0, 36]
So what is happening are, we
-
Loop through
ninnums -
Apply filter
if n > 2 -
Compute
n**2 if even else 0
Comments