Python Forum
Append 2d empty lists - 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: Append 2d empty lists (/thread-30401.html)



Append 2d empty lists - NMMST - Oct-19-2020

Hi there!

I wanted to store my functions result in a 2d list. The function returns 5 values and has to run 100 times in a for loop.
I tried to initiate a storage list by ding this:
list1 = [[]]*5
which returns list1 = [[], [], [], [], []]

However, when I want to append to one of those lists inside, all of them get the value appended
list1[0].append(3)
Would return: [[3], [3], [3], [3], [3]]
The strange thing is that I am able to add an object to a list and after that, the list becomes appendable
list1[0] = [1]
list1[0].append(3)
returns [[1, 3], [], [], [], []]

I solved the problem in a far less elegant way, by initiating a list like this
list1 = [[0],[1],[2],[3],[4]] 
and after appending, removing the first values.

However, this is not flexible and is time consuming to adjust if the problem changes.
Is there a more elegant/simple/flexible way to solve this problem?


RE: Append 2d empty lists - bowlofred - Oct-19-2020

Your first line has not made a list of 5 different lists inside, it's made a list with 5 copies of the same list inside.

>>> l = [[]] * 5
>>> l
[[], [], [], [], []]
>>> [id(x) for x in l]
[4464943816, 4464943816, 4464943816, 4464943816, 4464943816]
Instead you want to create a new list 5 different times. Perhaps:

>>> l = [[] for i in range(5)]
>>> l
[[], [], [], [], []]
>>> [id(x) for x in l]
[4464944008, 4464944648, 4464944456, 4464944328, 4464944200]
>>> l[2].append(3)
>>> l
[[], [], [3], [], []]



RE: Append 2d empty lists - NMMST - Oct-19-2020

(Oct-19-2020, 09:18 PM)bowlofred Wrote: Your first line has not made a list of 5 different lists inside, it's made a list with 5 copies of the same list inside.

>>> l = [[]] * 5
>>> l
[[], [], [], [], []]
>>> [id(x) for x in l]
[4464943816, 4464943816, 4464943816, 4464943816, 4464943816]
Instead you want to create a new list 5 different times. Perhaps:

>>> l = [[] for i in range(5)]
>>> l
[[], [], [], [], []]
>>> [id(x) for x in l]
[4464944008, 4464944648, 4464944456, 4464944328, 4464944200]
>>> l[2].append(3)
>>> l
[[], [], [3], [], []]

Thank you very much! This helps out a lot!