List comprehension is a concise way to create lists.
Basic syntax:
1# Without comprehension2squares = []3for x in range(10):4 squares.append(x ** 2)56# With comprehension7squares = [x ** 2 for x in range(10)]
With condition:
1even_squares = [x ** 2 for x in range(10) if x % 2 == 0]2# [0, 4, 16, 36, 64]
Nested loops:
1pairs = [(x, y) for x in range(3) for y in range(3)]2# [(0, 0), (0, 1), (0, 2), (1, 0), ...]
Other comprehensions:
1# dict2square_dict = {x: x**2 for x in range(5)}34# set5unique = {x for x in [1, 2, 2, 3, 3, 3]}67# generator (lazy)8squares_gen = (x**2 for x in range(10))