Why does this list of lists end up with the same values - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Why does this list of lists end up with the same values (/thread-19882.html) |
Why does this list of lists end up with the same values - alehak - Jul-18-2019 How can this be explained? x = [[]]*3 x[0].append('a') print(x)>>> returns [['a'], ['a'], ['a']] RE: Append working - stranac - Jul-18-2019 After you execute x = [[]]*3 , x is a list containing 3 references to the same list. Basically, you've given the inner list three names: x[0] , x[1] and x[2] .When you modify the list, you can see the change no matter which name you use. The same would happen if you did this: >>> a = b = [] >>> a.append(1) >>> b [1]You probably wanted to create 3 distinct lists, e.g.: x = [[] for _ in range(3)] RE: Why does this list of lists end up with the same values - perfringo - Jul-18-2019 You can read or watch Ned Batchelder's Python Names and Values. This should answer you question in pretty comprehensive way. |