Concatenation of many lists in Python [duplicate]
Suppose I have a function like this:
def getNeighbors(vertex)
which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:
listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
listOfNeighborsNeighbors.append(getNeighbors(neighborsVertex))
Is there a more pythonic way to do that?
As usual, the itertools module contains a solution:
>>> l1=[1, 2, 3]
>>> l2=[4, 5, 6]
>>> l3=[7, 8, 9]
>>> import itertools
>>> list(itertools.chain(l1, l2, l3))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[x for n in getNeighbors(vertex) for x in getNeighbors(n)]
or
sum(getNeighbors(n) for n in getNeighbors(vertex), [])
Appending lists can be done with + and sum():
>>> c = [[1, 2], [3, 4]]
>>> sum(c, [])
[1, 2, 3, 4]