Home > Software design >  How do I consolidate multiple lists (nested list) into a single list?
How do I consolidate multiple lists (nested list) into a single list?

Time:01-04

for example, I get

[[], [2, 3, 4, 5]]
[[1], [3, 4, 5]]
[[1, 2], [4, 5]]
[[1, 2, 3], [5]]
[[1, 2, 3, 4], []]

And I want to convert first list into [2,3,4,5], next [1,3,4,5], et cetera. I try to mutiply them all together but of course a list cannot mutiply a interger.

CodePudding user response:

Just for fun, if all your list is just one level deep (in your sample), you could try this trick: (or as prev. comment suggest)

list1 = [[], [2, 3, 4, 5]]
list1 = sum(list1, [])

print(list1)
# [2, 3, 4, 5]

list2 = [[1], [3, 4, 5]]
list2 = sum(list2, [])
print(list2)
# [1, 3, 4, 5]

CodePudding user response:

You can use itertools.chain:

>>> from itertools import chain
>>> list(chain.from_iterable([[1, 2], [4, 5]]))
[1, 2, 4, 5]
  • Related