Concatenating two lists - difference between '+=' and extend()
Solution 1:
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.
Solution 2:
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 fail
main()
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*
Solution 3:
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.listBar
a = 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