1

I read on this site that while appending elements to a list, say L, although the approaches:

L + [42] 

and

L.append(42)          

give the same result, the first approach is not same as the second and also that the first approach should never be used. Why is it so?

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 1
    *"We can see that the "+" operator is about 1268 slower than the append method"* - from the page you linked. It also offers a nice explanation of the difference. – vaultah Dec 01 '16 at 15:22

2 Answers2

5

L + [42] generates a new list, L.append(42) modifies the list L.

In practice, modifying is often needed, so while it is possible to do something like L = L + [42] for a new list to be generated and placed to the variable L (it's like making a copy of a picture sitting in a frame, modifying the copy and putting it into the same frame, destroying the original picture), L.append(42) is far more efficient (like changing the picture directly).

Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23
-1

You also can extend a list using the extend command:

a = [1 ,2, 3]
b = [4, 5]
a.extend(b)

a will be [1, 2, 3, 4, 5] and b stays the same.

daniboy000
  • 1,069
  • 2
  • 16
  • 26