Skip to content

Latest commit

 

History

History
33 lines (23 loc) · 799 Bytes

File metadata and controls

33 lines (23 loc) · 799 Bytes

List Comprehensions

Concise syntax for building lists. See List comprehension — Wikipedia.

Syntax

[expression for item in iterable if condition]

Covered

  • List comprehension with nested loops (building a 2D grid)
  • The shared-reference pitfall with [[0] * n] * m
  • Correct 2D list initialisation using comprehension

The pitfall

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 changed

Run

python list_comprehensions.py