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)modifiesa_listin place.a_list = a_list + b_listcreates a new list, then saves it to the namea_list. Note thata_list += b_listshould be exactly the same as theextendversion.Using
extendor+=is probably slightly faster, since it doesn’t need to create a new object, but if there’s another reference toa_listaround, it’s value will be changed too (which may or may not be desirable).