helpermethod helpermethod - 8 months ago 50
Python Question

Concatenating two lists - difference between '+=' and extend()

I've seen there are actually two (maybe more) ways to concatenate lists in Python:
One way is to use the extend() method:

a = [1, 2]
b = [2, 3]

the other to use the plus(+) operator:

b += a

Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (I've looked up the official Python tutorial but couldn't find anything anything about this topic).


The only difference on a bytecode level is that the .extend way involves a function call, which is slightly more expensive in Python than the INPLACE_ADD.

It's really nothing you should be worrying about, unless you're performing this operation billions of times. It is likely, however, that the bottleneck would lie some place else.