The Python Oracle

Concatenating two lists - difference between '+=' and extend()

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping

--

Chapters
00:00 Concatenating Two Lists - Difference Between '+=' And Extend()
00:32 Accepted Answer Score 310
00:53 Answer 2 Score 249
01:24 Answer 3 Score 78
02:29 Answer 4 Score 9
02:59 Thank you

--

Full question
https://stackoverflow.com/questions/3653...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#list #python

#avk47



ACCEPTED ANSWER

Score 310


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.




ANSWER 2

Score 249


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*




ANSWER 3

Score 78


+= only works if the statement would also work with an = sign, i.e. the left-hand side can be assigned to. This is because a += b actually becomes a = a.__iadd__(b) under the hood. So if a is something that can't be assigned to (either by syntax or semantics), such as a function call or an element of an immutable container, the += version will fail.

Example 1: Function calls

You can't assign to a function call (the syntax of Python forbids it), so you also can't += a function call's result directly:

list1 = [5, 6]
list2 = [7, 8]

def get_list():
    return list1

get_list().extend(list2)  # works
get_list() += list2  # SyntaxError: can't assign to function call

Example 2: Element of immutable container

A perhaps weirder case is when the list is an element of an immutable container, e.g. a tuple:

my_tuple = ([1, 2], [3, 4], [5, 6])
my_tuple[0].extend([10, 11])  # works
my_tuple[0] += [10, 11]  # TypeError: 'tuple' object does not support item assignment

Since you can't do my_tuple[0] = something, you also can't do +=.

To sum up, you can use += if you can use =.




ANSWER 4

Score 9


I would say that there is some difference when it comes with numpy (I just saw that the question ask about concatenating two lists, not numpy array, but since it might be a issue for beginner, such as me, I hope this can help someone who seek the solution to this post), for ex.

import numpy as np
a = np.zeros((4,4,4))
b = []
b += a

it will return with error

ValueError: operands could not be broadcast together with shapes (0,) (4,4,4)

b.extend(a) works perfectly