Comprehensions
Python offers concise syntax for building sequences.
- List comprehensions build lists with an expression, loop, and optional condition.
- Example: squares of even numbers.
-
Also useful: dict comprehensions (
{k: v for ...}) and set comprehensions ({x for ...}).
Example
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]