Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Append 2d empty lists
#1
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?
Reply


Messages In This Thread
Append 2d empty lists - by NMMST - Oct-19-2020, 08:56 PM
RE: Append 2d empty lists - by bowlofred - Oct-19-2020, 09:18 PM
RE: Append 2d empty lists - by NMMST - Oct-19-2020, 09:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Syntax when initializing empty lists Mark17 2 1,355 Jun-02-2022, 04:09 PM
Last Post: Mark17
  Better way to append frames from a video to multiple lists? Balaganesh 0 1,838 May-13-2021, 07:37 AM
Last Post: Balaganesh
  Lists + Empty Lists Pytho13 15 5,476 Mar-26-2021, 08:52 PM
Last Post: pythonprogrammer1101935
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,361 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Cant Append a word in a line to a list err "str obj has no attribute append Sutsro 2 2,568 Apr-22-2020, 01:01 PM
Last Post: deanhystad
  append list to empty array SchroedingersLion 1 2,167 Feb-02-2020, 05:29 PM
Last Post: SchroedingersLion
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,254 Mar-20-2019, 08:01 PM
Last Post: stillsen
  append elements into the empty dataframe jazzy 0 2,095 Sep-26-2018, 07:26 AM
Last Post: jazzy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020