简体   繁体   中英

Python- Changing element within a list of lists

I'm trying to change an element within a list of lists. Here is my code and I'm using python version 3:

myboard = []

colList = []
#makes a 2D list/array of the rows and colums
for i in range(columns):
    colList.append(0)

for x in range(rows):
    myboard.append(colList)


myboard[0][1] = 999

print(myboard[0][1])

When I do this, it changes all the 1'th elements in each list to 999. Help please!

your error is due the fact that colList is the pointer to a list and not a list itself. If you want to have "independent" list in each element of myboard you have to replace
myboard.append(colList) with myboard.append(colList.copy())

In this way each element of myboard will be a copy of the list.

Short Solution:


As Donbeo pointed out you must replace myboard.append(colList) with myboard.append(colList.copy)

Why:


Because in python when you make a reference (with in bar) to any mutable object (lets call it foo) its a exact replica, forever. So for instance foo = [1,2,3] and bar = [foo, foo, foo] makes bar = [[1,2,3],[1,2,3],[1,2,3]] . Now lets say you change foo to [3,2,1] then bar updates and becomes [[3,2,1],[3,2,1],[3,2,1]] . So, what is wrong with bar[0][1] = 999 . Well, bar[0] == foo therefore bar[0][1] == foo[1] .
Now in python there's a easy fix! Lists have a copy method which creates a replica that does not change when foo does. For example foo = [1,2,3] and bar = [foo.copy, foo.copy] ; now try bar[0][1] = 999 . ITS ALIVE It works correctly. Now bar[1][1] != bar[0][1] .

Demo


Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM