Why use extend when you can just use the += operator? Which method is best? Also what's the best way of joining multiple lists into one list
#my prefered way
_list=[1,2,3]
_list+=[4,5,6]
print _list
#[1, 2, 3, 4, 5, 6]
#why use extend:
_list=[1,2,3]
_list.extend([4,5,6])
print _list
#[1, 2, 3, 4, 5, 6]
_lists=[range(3*i,3*i+3) for i in range(3)]
#[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
#my prefered way of merging lists
print sum(_lists,[])
#[0, 1, 2, 3, 4, 5, 6, 7, 8]
#is there a better way?
from itertools import chain
print list(chain(*_lists))
#[0, 1, 2, 3, 4, 5, 6, 7, 8]
+=
can only be used to extend one list by another list, while extend
can be used to extend one list by an iterable object
e.g.
you can do
a = [1,2,3]
a.extend(set([4,5,6]))
but you can't do
a = [1,2,3]
a += set([4,5,6])
For the second question
[item for sublist in l for item in sublist] is faster.
see Making a flat list out of list of lists in Python
You may extend()
a python list with a non-list object as an iterator. An iterator is not storing any value, but an object to iterate once over some values. More on iterators here.
In this thread, there are examples where an iterator is used as an argument of extend()
method: append vs. extend
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