Comprehensions and generator expressions [ref]
Problem
- Square
[1, 2, 3] and filter even values from [1, 2, 3, 4] with list comprehensions.
- Map
[10, 20] to indices with a dictionary comprehension.
- Build a set of lowercase characters from
"aAbB".
- Sum the positive consecutive gains in
[3, 5, 4, 8] with a generator expression.
- Make a square generator for
0, 1, and 2, then exhaust it twice.
- Flatten
[[1, 2], [3, 4]].
Python solution
[x * x for x in [1, 2, 3]] # [1, 4, 9]
[x for x in [1, 2, 3, 4] if x % 2 == 0] # [2, 4]
{x: i for i, x in enumerate([10, 20])} # {10: 0, 20: 1}
{ch.lower() for ch in "aAbB"} # {'a', 'b'}
prices = [3, 5, 4, 8]
sum(max(0, prices[i] - prices[i - 1]) for i in range(1, len(prices)))
# 6
squares = (x * x for x in range(3))
list(squares) # [0, 1, 4]
list(squares) # []
[x for row in [[1, 2], [3, 4]] for x in row] # [1, 2, 3, 4]
Links