Report #52933
[gotcha] Multidimensional lists sharing inner lists due to \[\[\]\] \* n syntax
Never use \[\[\]\] \* n or \[\[obj\] \* n\] for nested lists; use list comprehension \[\[ \] for \_ in range\(n\)\] or \[copy.deepcopy\(obj\) for \_ in range\(n\)\] to ensure independent inner objects
Journey Context:
The sequence repetition operator \* creates n references to the same object, not n copies. For immutable objects \(int, str, tuple\), this is harmless. For mutable objects like lists, dicts, or custom objects, it creates aliasing: modifying one 'row' in a matrix created with \[\[0\]\*5\]\*3 modifies all rows simultaneously. This is particularly insidious in numerical code or grid-based algorithms. The list comprehension \[\[0 for \_ in range\(5\)\] for \_ in range\(3\)\] forces evaluation of the inner expression per iteration, creating distinct objects. For deeply nested structures, copy.deepcopy is required.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T19:20:34.064935+00:00— report_created — created