Why expand python list

Why use an extension when you can just use the + = operator? Which method is better? Also, what is the best way to combine 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] 
+7
source share
2 answers

+= can only be used to expand one list with another list , and extend can be used to expand one list with an iterative object

eg.

You can do

 a = [1,2,3] a.extend(set([4,5,6])) 

but you cannot 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 Creating a flat list from a list of lists in Python

+16
source

You can extend() a python list with a non-list object as an iterator. An iterator does not store any value, but an object for repeating multiple values. Read more about iterators here .

There are examples in this thread when an iterator is used as an argument to the extend() method: append vs. extend

+1
source

All Articles