0
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?

Frank Vel
  • 1,202
  • 1
  • 13
  • 27

2 Answers2

2

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)]  
Nizam Mohamed
  • 8,751
  • 24
  • 32
1

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.

user1537085
  • 404
  • 5
  • 18