Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
Björn Pollex Avatar asked Jun 11 '10 09:06

Björn Pollex


People also ask

How do you concatenate 3 lists in Python?

You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. What is this? Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.

How do I combine multiple lists into one list?

Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.

Can we concatenate lists in Python?

The most conventional method to perform the list concatenation, the use of “+” operator can easily add the whole of one list behind the other list and hence perform the concatenation. List comprehension can also accomplish this task of list concatenation.


1 Answers

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] 
like image 98
Jochen Avatar answered Sep 16 '22 13:09

Jochen