Concise syntax for building lists. See List comprehension — Wikipedia.
[expression for item in iterable if condition]- List comprehension with nested loops (building a 2D grid)
- The shared-reference pitfall with
[[0] * n] * m - Correct 2D list initialisation using comprehension
L = [[0] * 3] * 2 # WRONG — both rows are the same object in memory
L[0][1] = 10
print(L) # [[0, 10, 0], [0, 10, 0]] — both rows changed!
L = [[0] * 3 for _ in range(2)] # CORRECT — each row is independent
L[0][1] = 10
print(L) # [[0, 10, 0], [0, 0, 0]] — only first row changedpython list_comprehensions.py