Combining Lists in Python 3

I am reading Immersion in Python 3 and in the lists section, the author claims that you can combine lists using the "+" operator or by calling the extend () method. Are these the same two different ways to do the operation? Any reason I should use one or the other?

>>> a_list = a_list + [2.0, 3] >>> a_list.extend([2.0, 3]) 
+6
source share
1 answer

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

Using extend or += probably a little faster, since it does not need to create a new object, but if there is another link to a_list around, this value will also be changed (which may or may not be desirable).

+12
source

All Articles