Concatenating lists in Python 3

Question:

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])  
Asked By: Ci3

||

Answers:

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).

Answered By: Blckknght

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

Answered By: Padmini
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.