python – Concatenating two lists – difference between += and extend()

python – 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.

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

You cant 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()

Its 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*

python – Concatenating two lists – difference between += and extend()

You can chain function calls, but you cant += 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: cant assign to function call

Leave a Reply

Your email address will not be published.