Python Forum
python nested list assignment weird behavior - 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: python nested list assignment weird behavior (/thread-7584.html)



python nested list assignment weird behavior - eyalk1 - Jan-16-2018

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



RE: python nested list assignment weird behavior - buran - Jan-16-2018

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]]
>>> 



RE: python nested list assignment weird behavior - wavic - Jan-16-2018

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