Does the way you define nested lists in python matter? [duplicate]

Does the way you define nested lists in python matter? [duplicate]
python
Ethan Jackson

Python noob here. Any expert help would be greatly appreciated.

Let's assume that I defined a list, list1 as

list1 = [[0]*10]*10

and defined a list2 as

list2 = [[0]*10 for i in range(10)]

aren't these pretty much two equivalent ways of defining a nested list? Is there any reason these two lists would be different in some way?

Answer

The two nested list definitions look similar but behave very differently due to how Python handles object references.

  • list1 = [[0]*10]*10 creates 10 references to the same inner list.

  • list2 = [[0]*10 for i in range(10)] creates 10 independent inner lists.

This affects behavior when you modify elements in the nested list. Always prefer the list comprehension (list2) when you want independent rows.

Related Articles