Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why extend a python list

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]
like image 464
robert king Avatar asked Jan 08 '12 05:01

robert king


2 Answers

+= 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

like image 121
qiao Avatar answered Nov 16 '22 18:11

qiao


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

like image 28
kiriloff Avatar answered Nov 16 '22 16:11

kiriloff