0

I encountered a problem with generating a grid of integers in Python. My code:

c = [[0] * 3] * 3
print c

c[0][0] = 1
print c

The first print statement prints as follows, which is the grid I want

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

The second print statement prints as follows, which is not what I want. I just wanted to change grid[0][0] to 1, but not every head of the lists in grid.

[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

How do I generate a grid in a quick way, without this kind of modification issue?

Thank you!

Matthew Woo
  • 1,288
  • 15
  • 28
Fan
  • 1
  • 2
    Possible duplicate of [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly) – khelwood Nov 04 '16 at 19:38
  • a = [] for i in range(3): a.append(0) b = [] for i in range(3): b.append(a[:]) print b b[0][0] = 1 print b. This code performs well, but it is too tedious. – Fan Nov 04 '16 at 19:40
  • `c = [[0]*3 for _ in xrange(3)]` - see duplicate for explanation. – khelwood Nov 04 '16 at 19:40

0 Answers0