Search code examples
pythonlistmergeappendextend

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]

Solution

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