2

If I build a nested list:

nested_list = 3*[[]]

and if I then add elements to it

  1. nested_list[1] += [1, 2, 3]. returns:[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
  2. nested_list[1] = nested_list[1] + [1, 2, 3]. returns: [[ ], [1, 2, 3], [ ]]

I would have expected to obtain the result of case 2 for both operations.

Why do I obtain a different result in case 1? Is this a design choice of python? What is the logic of the result in case 1?

danjjl
  • 432
  • 1
  • 5
  • 16
  • 4
    The core problem here is that `nested_list = 3*[[]]` is a bad way to create a list of lists: http://stackoverflow.com/q/240178/3001761 – jonrsharpe Jan 16 '17 at 17:16

1 Answers1

4

In the first example, you update the reference of nested_list[1]. Since all 3 slots use the same reference, you see your change 3 times.

In the second example, you're not appending in-place: you create another reference for nested_list[1], which updates only the middle slot of the list of lists, leaving the others with the old reference.

Note that nested_list = 3*[[]] to build a nested list is not very useful. You may want to create separate references for all sublists like this:

nested_list = [[] for _ in range(3)]

Now both operations yield the same result (but the preferred way is nested_list[1] += ... since it is way more performant)

This doesn't apply to immutable objects like strings, ints, floats, where the * operator is not a problem. Applying in-place addition only changes the item it applies to.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219