7

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]
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116

2 Answers2

16

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

Community
  • 1
  • 1
qiao
  • 17,941
  • 6
  • 57
  • 46
1

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

Community
  • 1
  • 1
kiriloff
  • 25,609
  • 37
  • 148
  • 229