This story was originally published on HackerNoon at:
https://hackernoon.com/why-doesnt-create-independent-nested-lists-in-python-the-hidden-list-multiplication-trap.
Learn why [[0,0,0]] * 3 in Python secretly shares one list across all rows, and how to build truly independent nested lists the right way.
Check more stories related to programming at:
https://hackernoon.com/c/programming.
You can also check exclusive content about
#python,
#python-programming,
#python-lists,
#python-shared-references,
#python-mutable-objects,
#python-list-comprehension,
#mutable-list-bug-in-python,
#hackernoon-top-story, and more.
This story was written by:
@sohelalam79. Learn more about this writer by checking
@sohelalam79's about page,
and for more stories, please visit
hackernoon.com.
[x] * n does not create n independent copies of x. It creates one object and repeats a reference to that same object n times. For immutable elements like numbers or strings, this is harmless because any "change" actually rebinds the slot to a new object. For mutable elements like lists or dicts, every slot points to the exact same object, so mutating one slot mutates all of them. The fix is to use a list comprehension — [x for _ in range(n)] — which creates a genuinely new object on each iteration. Key takeaway: * repeats references, not values.