Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two lists inside nested list Python? [duplicate]

How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

like image 774
Ada Avatar asked Mar 18 '26 07:03

Ada


1 Answers

You can use operator.concat() to group 2 separate lists into one and itertools.starmap() to iterate over main list and unpack inner lists:

from operator import concat
from itertools import starmap

result = list(starmap(concat, lists_of_lists))

You can do it also without imports using built-in map() function and lambda expression (but why?):

result = list(map(lambda x: x[0] + x[1], lists_of_lists))

You can also use chain.from_iterable():

from itertools import chain

result = list(map(list, map(chain.from_iterable, lists_of_lists)))

But if you want want to patch code you've written to work as you expected:

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
new = []
for sub_list in lists_of_lists:
    new_item = []
    for item in sub_list:
        for element in item:
           new_item.append(element)
    new.append(new_item)
like image 198
Olvin Roght Avatar answered Mar 19 '26 20:03

Olvin Roght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!