views:

68

answers:

2

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

+1  A: 

According to the Zen of Python:

Simple is better than complex.

b += a is more simple than b.extend(a).

The builtins are so highly optimized that there's no real performance difference.

leoluk
I don't see any way that one is simpler than the other. They're both equivalently completely trivial.
Glenn Maynard
+4  A: 

The only difference on a bytecode level is that .extend way involves 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.

SilentGhost