1

What is the difference between the two arrays created with

array1 = [[0] * 2] * 3

and

array2 = [[0 for _ in range(2)] for _ in range(3)]

I'm asking because they display different behavior (such as, when I increment an integer in array1, it will increment every single value in that column).

2 Answers2

1

array1 is making a list of references to a single list while array2 is constructing new lists by value. array1 = [[0] * 2] * 3 is saying "take 3 pointers to the same list (in our case [0,0]) and populate a new list with them." So really its the same list being represented at three different indices, therefore if you change any index of array1 all three values will change, as they are all the same list!

Meanwhile, array2 = [[0 for _ in range(2)] for _ in range(3)] is making three distinct lists all with the same values, in our case [0,0].

thedeg123
  • 408
  • 2
  • 5
  • 11
  • 1
    `array2` isn't making "copies" at all. It's making several new arrays that all happen to contain the same data. – shadowtalker Jun 25 '20 at 15:46
  • @shadowtalker I could see how that language could be misleading. I was really referencing python's by reference vs by value discrepancy. Ie as all variables are pointers, they all point to the same instance of the object until forced to be unique. – thedeg123 Jun 25 '20 at 15:50
  • 1
    Please avoid to vaguely describe Python via pointers. The terminology is incredibly overloaded and can be very misleading to people of various backgrounds. Python, the language, does not have a concept of pointers, nor does it have distinct reference and value types. ``[0] * 2`` is *an object*, and ``[[0] * 2] * 3`` contains *this very same object* three times. – MisterMiyagi Jun 25 '20 at 16:01
-1

Check this out: https://riptutorial.com/python/example/12259/list-multiplication-and-common-references

Basically, when you multiply a list (as a commenter noted, they are technically lists in Python, not arrays) by an integer, python will insert the same reference multiple times. That is, when [0]*2 is run, instead of creating an additional zero, it inserts an additional reference to that first zero.

The second version creates additional instances of numbers / lists each time it loops, which is why (even though it's the same expression being evaluated for the content of the list) the references are independent.

Hope this helps!

minerharry
  • 101
  • 8