Comprehensions in Python provide a concise way to create lists, dictionaries, and sets using a single readable expression. They make code more elegant and efficient, especially when working with iterables.
squares = [x**2 for x in range(10)]
print(squares)
evens = [x for x in range(20) if x % 2 == 0]
print(evens)
pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)
results = [x if x > 5 else 0 for x in range(10)]
print(results)
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
print(flat)
nums = [1, 2, 3]
squares = {n: n**2 for n in nums}
print(squares)
nums = range(10)
even_squares = {n: n**2 for n in nums if n % 2 == 0}
print(even_squares)
d = {'a': 1, 'b': 2}
swapped = {v: k for k, v in d.items()}
print(swapped)
unique_squares = {x**2 for x in [-2, -1, 0, 1, 2]}
print(unique_squares)
filtered = {x for x in range(10) if x % 3 != 0}
print(filtered)
Comprehensions are powerful tools for writing clear, concise, and performant Python code when working with iterables.