0

I have the following simple 2D lists program:

rowMatrix = [0]*4
matrix = [rowMatrix]*4

for a in range(4):
    for b in range(4):
        matrix[a][b] = random.randrange(0,2)
print(matrix)`

It seems like it would put random numbers (0, 1) in all 16 cells of the 4x4 array. But all 4 rows are identical every time. What's wrong?

user2268716
  • 13
  • 1
  • 5
  • 1
    See [How do I create a multidimensional list](http://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list) in the official FAQ. – abarnert Nov 07 '13 at 23:34
  • This is a dup of about 300 other questions. I've linked one of them, but a quick search, or just scanning through the "Related" links, should turn up the rest. – abarnert Nov 07 '13 at 23:36
  • @AshishNitinPatil: If you have enough rep, please vote to close the question as a dup, instead of just adding a comment. – abarnert Nov 07 '13 at 23:38
  • I flagged it before adding the comment. The flag suggested a question which was also a duplicate. I can't cast a close vote as yet. – shad0w_wa1k3r Nov 07 '13 at 23:40
  • Thanks. Python lists are less intuitive than Java 2D arrays. – user2268716 Nov 07 '13 at 23:43

1 Answers1

2

The following line creates four list elements which are actually the same list:

matrix = [rowMatrix]*4

This means modifying matrix[0][0] also modifies the other lists.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180