2

Why are the two outputs different:

The only difference in the 2 approaches is the way the matrix has been initialized. I expect to get the same output in both the scenarios but the output seems to be different?

Is there something I am missing?

x = 4
table = [[0]*(x)]*x
for i in range(x):
    table[i][i] = 1
print(table)

table: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

x = 4
table = [[0]*x for i in range(x)]
for i in range(x):
    table[i][i] = 1
print(table)

table: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

J_H
  • 17,926
  • 4
  • 24
  • 44
  • 1
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – AMC Jan 06 '20 at 02:23
  • 1
    Another one: https://stackoverflow.com/q/6688223/11301900. – AMC Jan 06 '20 at 02:24
  • Was this question just for learning purposes, or as part of a larger program? – AMC Jan 06 '20 at 02:25
  • @AMC it was for learning purpose. Thanks for providing the links :) – mvsnbharath Jan 06 '20 at 02:51

1 Answers1

1

You are having trouble with pointers to a common object.

Consider this (simpler) case:

>>> a = list(range(4))
>>> b = a
>>> b[2] = 9
>>> a
[0, 1, 9, 3]

Why does changing b alter the contents of a ?!? Because they are both names for the same mutable object, a list.


Your second example does what you want. The list comprehension produces a new list object each time you iterate.

Your first example produces a single list of length four, and then produces four pointers to the same list. Changing the list via one of its four names will produce a change in all four rows of printed output.

J_H
  • 17,926
  • 4
  • 24
  • 44