helpermethod helpermethod - 2 years ago 96
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]
b.extend(a)


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).

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download