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?
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With