0
L = [1,2,3,4]

L.append(13) # (1)
L = L + [13] # (2)

What is difference in above statements?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Memorial
  • 57
  • 6

2 Answers2

5

L.append(13) appends 13 to an existing list.

L = L + [13] creates a new list.

stranac
  • 26,638
  • 5
  • 25
  • 30
2

L.append(13) adds a single item, the int 13, to the end of the list.

L = L + [13] adds every item in a secondary list to the end of the first list. So you could have written L = L + [12, 4, 13] and it would add all three.

Moreover, append adds 13 to the end of an existing list....in the computer's memory, L is still the same list, just with a new item added into it. But whenever you use the = operator*, you're creating something new. So L = L + [13] is creating a new list in the computer's memory, assigning it the name L and filling it with the contents of the old L concatenated with the list [13].

*If you do var1 = var2, however, it's not creating something new but rather assigning the name var1 to point to the same place in memory as var2.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • 1
    "But whenever you use the = operator, you're creating something new." This glosses over the difference between rebinding and mutation, and makes it seem like `M = L` will create a new list in the computer's memory. – DSM Dec 13 '15 at 18:52