def list():
mylist = [[0,0,0,0]]*3
mylist[1][2] = 8013
print(mylist)
Output:
[[0,0,8013,0],[0,0,8013,0],[0,0,8013,0]]
Wanted output:
[[0,0,0,0],[0,0,8013,0],[0,0,0,0]]
How do I fix this?
def list():
mylist = [[0,0,0,0]]*3
mylist[1][2] = 8013
print(mylist)
Output:
[[0,0,8013,0],[0,0,8013,0],[0,0,8013,0]]
Wanted output:
[[0,0,0,0],[0,0,8013,0],[0,0,0,0]]
How do I fix this?
Use eval
on repr
.
mylist = eval(repr([[0,0,0,0]]*3))
or use list comp to produce the list
mylist = [[0,0,0,0] for _ in range(3)]
Use mylist = [[0 for _ in xrange(4)] for _ in xrange(3)]
Using *
will cause Python to use the same object for the whole list, and that's why when you change any one of the element in the list, you are changing the rest of them.