Skip to content Skip to sidebar Skip to footer

Creating And Working With List Of Lists Of Lists: In Python

I'm new with Python and for some needs I am trying to figure out how to work with list of lists of lists. Here's what am I doing: segment_coef = [[list()]*4]*17 print segment_coef

Solution 1:

Python is using the same list 4 times, then it's using the same list of 4 lists 17 times!

The issue here is that python lists are both mutable and you are using (references to) the same list several times over. So when you modify the list, all of the references to that list show the difference.

Depending on how/where you get your data from, depends on the best way to fix it, but something like:

lols = []
for i in range(17):
    lols.append([1,2,3,4])
# lols is not a list of 17 lists, each list contains the same data but they are different lists
lols[0][0] = 99
# Now only the first element from the first list is updated.

To be clear, the issue comes from doing [list() * 4], which construsts the list ones (using list) and then repeats it 4 times. If you did [list(), list()m list(), list()] you would get 4 different (but all empty) lists, or, more pythonically, [list() for _ in range(4)] or just [[] for _ in range(4)]


Solution 2:

There are a couple of ways to create a list of 17 lists of 4 sublists each

the shortest would be

[[list() for i in range(4)] for j in range(17)] 

If you do this, your appends will work as you want them to

If you're familiar with languages like C or Java that don't have list comprehensions, this way might look more familiar to you:

l = []
for j in range (17):
  k = []
  for i in range (4):
    k.append(list())
  l.append (k)

This is also acceptable, but for many python heads, the list comprehension is preferable. The list comp should be performance-wise at least as good as the comprehension.


Post a Comment for "Creating And Working With List Of Lists Of Lists: In Python"