Python Forum

Full Version: python nested list assignment weird behavior
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
mat was initialized like this:
mat = [[0]*26]*5
The problem is that after an inner loop iteration all the rows in mat get changed the same but i clearly stated that only the ith row should change.
the problematic lines are the ones after the # comment
please help me :(

def fill_letters_matrix(mat, word_list):
        for i in range(len(mat)):
            for j, item in enumerate(word_list):
                if j != len(word_list)-1:
                    if len(item)-i-1 < 0:
                        continue
                    #the jibrish in the second brackets works,so no need to dive in...
                    mat[i][ord(item[len(item)-i-1])-ord("A")] += 1
                else:
                    mat[i][ord(item[len(item) - i-1]) - ord("A")] -= 1
Please, read this https://nedbatchelder.com/text/names1.html
the way you initialize it is a problematic, because actually every row is a reference to the same 26-element list (row).
>>> mat = [[0]*6]*5
>>> print mat
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> mat[1][1]=1
>>> mat
[[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0]]
>>> mat = [[0]*6 for _ in range(5)]
>>> mat
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> mat[1][1] = 1
>>> mat
[[0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> 
In [1]: mat = [[0]*26]*5

In [2]: id(mat[0])
Out[2]: 140082606853896

In [3]: id(mat[1])
Out[3]: 140082606853896
As you can see the list elements are one object.
Use list comprehension instead.

mat = [0 for _ in range(26)] for range(5)]]
See this video: https://www.youtube.com/watch?v=F6u5rhUQ6dU