Concatenating two lists - difference between '+=' and extend()
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.
You can't use += for non-local variable (variable which is not local for function and also not global)
def main(): l = [1, 2, 3] def foo(): l.extend([4]) def boo(): l += [5] foo() print l boo() # this will failmain()
It's because for extend case compiler will load the variable l
using LOAD_DEREF
instruction, but for += it will use LOAD_FAST
- and you get *UnboundLocalError: local variable 'l' referenced before assignment*
You can chain function calls, but you can't += a function call directly:
class A: def __init__(self): self.listFoo = [1, 2] self.listBar = [3, 4] def get_list(self, which): if which == "Foo": return self.listFoo return self.listBara = A()other_list = [5, 6]a.get_list("Foo").extend(other_list)a.get_list("Foo") += other_list #SyntaxError: can't assign to function call