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, whileextendcan be used to extend one list by an iterable objecte.g.
you can do
but you can’t do
For the second question
see Making a flat list out of list of lists in Python