Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating lists in Python 3

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])  
like image 330
Ci3 Avatar asked Jan 13 '13 05:01

Ci3


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

like image 91
Blckknght Avatar answered Nov 20 '22 05:11

Blckknght