21

I'm reading Dive into Python 3 and at the section of lists, the author states that you can concatenate lists with the "+" operator or calling the extend() method. Are these the same just two different ways to do the operation? Any reason I should be using one or the other?

>>> a_list = a_list + [2.0, 3]
>>> a_list.extend([2.0, 3])  
1
  • 2
    overridden + operator gives the result in another list, it's not an in-place addition. Whereas, extend is an in-place modification to the list.. The usage should be primarily on your logic, and probably on the size of your list... Commented Jan 13, 2013 at 6:02

2 Answers 2

36

a_list.extend(b_list) modifies a_list in place. a_list = a_list + b_list creates a new list, then saves it to the name a_list. Note that a_list += b_list should be exactly the same as the extend version.

Using extend or += is probably slightly faster, since it doesn't need to create a new object, but if there's another reference to a_list around, it's value will be changed too (which may or may not be desirable).

0

In the code below, I have defined 3 functions for each of the three ways to concatenate 2 lists. Note that func1 and func3 , both modify list1 when you print it after calling either of the functions. While, when you call func2, and then you print list1, it remains the same as before.

list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]


def func1(a_list, b_list):
    (a_list.extend(b_list))
    return(a_list)


def func2(a_list, b_list):
    a_list = a_list + b_list
    return (a_list)


def func3(a_list, b_list):
    a_list += b_list
    return (a_list)



print(func2(list1, list2))  #does not change list1   
print(list1)       # list1 is different from return value of func3

But with any of the calls below:

  1. print(func3(list1, list2)) print(list1) #list1 is same as the return value of func3

  2. print(func1(list1, list2)) print(list1) #list1 is same as the return value of func1

1
  • The examples are correct, however, it doesn't help to understand the original question. By adding functions, the question will be related to the scope of the variables too. print(func2(list1, list2)) prints the function variable of a_list which is the output of func2, and a different variable than list1. If you want to get a similar result, you may write something like list1 = func2(list1, list2); which saves the function output to list1. Commented Feb 8, 2023 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.