Python: Combining a list of lists
Question:
Suppose I have a list of lists, like [[1, 2], [3, 4], [5, 6], [7, 8]]
. What is the most elegant way in python to get [1, 2, 3, 4, 5, 6, 7, 8]
?
Answers:
res=[]
for item in mylistOfList:
res+=item
myCombinedList = []
[myCombinedList.extend(inner) for inner in mylistOfLists]
Or:
import itertools
myCombinedIterable = itertools.chain.from_iterable(mylistOfLists)
myCombinedList = list(myCombinedIterable)
Suppose I have a list of lists, like [[1, 2], [3, 4], [5, 6], [7, 8]]
. What is the most elegant way in python to get [1, 2, 3, 4, 5, 6, 7, 8]
?
res=[]
for item in mylistOfList:
res+=item
myCombinedList = []
[myCombinedList.extend(inner) for inner in mylistOfLists]
Or:
import itertools
myCombinedIterable = itertools.chain.from_iterable(mylistOfLists)
myCombinedList = list(myCombinedIterable)