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])
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With