Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple nested lists Python

Tags:

python

list

I have a block of code that gives me a list that has some triple nested lists within it:

my_list = [[['item1','item2']], [['item3', 'item4']]]

And I would like to make it:

my_list = [['item1','item2'], ['item3', 'item4']]

Any suggestions?

like image 574
John Bucel Avatar asked Dec 13 '17 06:12

John Bucel


1 Answers

A simple, but efficient way is to flatten your triple nested list with itertools.chain.from_iterable:

>>> import itertools
>>> my_list = [[['item1','item2']],[['item3','item4']]]
>>> my_list = list(itertools.chain.from_iterable(my_list))
>>> my_list
[['item1', 'item2'], ['item3', 'item4']]

Which has O(n)complexity for a list of size n.

like image 172
RoadRunner Avatar answered Sep 16 '22 18:09

RoadRunner