0

I come across the following python puzzle:

  x=4*[[]] # x is now [[],[],[],[]]
  for i in range(len(x)): x[i]+=[i];
  print x;
  # this returns [[0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3]]

now if I do instead:

  x=[[],[],[],[]];
  for i in range(len(x)): x[i]+=[i];
  print x;
  # this returns [[0],[1],[2],[3]]

The question is, why?

I also find that if the code is changed to

  x[i] = x[i] + [i]

then we have in both cases

  [[0],[1],[2],[3]]  

Does someone know why python behaves in this way?

Edit: the first half of my question is answered in the duplicate reference, and the second half is explained by @joriki below.

  • 1
    The question given as a duplicate only addresses the first part of the question, regarding the list behaviour. It doesn't address the subtlety of the assignment operator `+=`. As there are websites that claim that `c+=a` is equivalent to `c = c + a` (e.g. [this one](http://www.tutorialspoint.com/python/assignment_operators_example.htm), the first Google hit for "python assignment operators"), it would be worthwhile to explain here that `x[i]+=[i]` only affects the value of `x [i]` whereas `x[i] = x[i]+[i]`affects the reference. Thus I suggest the question should be reopened. – joriki Apr 29 '16 at 08:14
  • @joriki thank you for the clarification for the second half. Why not put this as an answer – Petite Etincelle Apr 29 '16 at 08:25
  • Because the question has been closed as a duplicate, so I can no longer post an answer. – joriki Apr 29 '16 at 08:31
  • @Martijn Pieters thank you for the quick reaction for the reference. As explained by joriki, could you reopen my question? – Petite Etincelle Apr 29 '16 at 08:35
  • @PetiteEtincelle: this is why you should always focus your question on *one problem at a time*. The second issue is a duplicate too, but I can only dupe you to one post at a time. – Martijn Pieters Apr 29 '16 at 08:50
  • See [Why does += behave unexpectedly on lists?](http://stackoverflow.com/q/2347265) for an in-depth explanation as to what `+=` augmented assignment does for lists. – Martijn Pieters Apr 29 '16 at 08:51
  • @MartijnPieters Get it. Actually I didn't know that I was asking two questions until you both enlightened me. – Petite Etincelle Apr 29 '16 at 11:41

0 Answers0