0

I was wondering: is there any difference between these two methods of appending an element to a list in python:

L = L + [1] and L.append(1) ?

I mean in a computational way : for example maybe the first method reallocate memory for a new list with size + 1 then copies the content of L into it then append 1. Or is it rather a linked list where we update the pointer of the next element in the last item of the list. In the latter I think there is no difference (or is there any ?)

Thanks

BoarGules
  • 16,440
  • 2
  • 27
  • 44
MrMaxPayne
  • 173
  • 5
  • Python lists are internally arrays. `L = L + [1]` has to allocate a new array and copy all the elements; it has `O(n)` complexity. `L.append(1)` is built such that it only reallocates infrequently; it has `O(1)` amortized complexity. – NPE Apr 15 '19 at 07:38
  • In simpler words: in the first way you create a new list, in the second way you modify the original list, therefore the second one is fast – luca.vercelli Apr 15 '19 at 07:55

0 Answers0