-1

Could somebody give a explanation why the increment operation behave like following ?

>>> a = [ [0]*4 ] * 3

>>> print a

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

>>> a[1][1] += 1

>>> print a

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

I was expected a = [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]

I understand that numpy.array would give me expected result, but I really want to know why nested list doesn't...

Bach
  • 6,145
  • 7
  • 36
  • 61

3 Answers3

1

Observe this:

In [9]:

a = [ [0]*4 ] * 3
In [10]:

map(id, a)
Out[10]:
[4382548912, 4382548912, 4382548912]

You think you have 3 lists, but in fact you have one list, 3 times. Therefore when you change the value of the 1st element of one list, all the first elements will be changed.

CT Zhu
  • 52,648
  • 17
  • 120
  • 133
0

You have three references to the same sublist rather than three separate lists.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

That's all true, and yet, it remains surprising and counterintuitive, I think. Yes, there are 3 copies of 1 list; however, this one list is itself 4 copies of a single-element list, so by the same "reasoning" or excuse-making, why doesn't a[1][1] = 1 set all 4 elements of the inner list, and thus all 12 atomic elements, equal to 1 ;)

Deep vs shallow, I suppose, but I think this makes it difficult to claim, "Oh, just think about it, you'll realize it's really the correct behavior." The behavior that is thus implemented has its place, but I doubt it's the typical use case, so for it to be the default makes it a sharp corner (imho, of course).

BrianO
  • 1,496
  • 9
  • 12