Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a list of lists from a list of list of lists without "flattening"

I’ve got an inner nested list as shown below.

test_list = [[['1']], [['2', '2']], [['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']], [['7', '7'], ['8'], ['7'], ['1'], ['7', '7']], [['7', '7'], ['8'], ['7'], ['7', '7']], [['2', '2']]]

I’m not looking out to flatten this list per-say. I would rather like to return a new list which would look like the new_list variable expressed below.

new_list = [['1'], ['2', '2'], [['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']], [['7', '7'], ['8'], ['7'], ['1'], ['7', '7']], [['7', '7'], ['8'], ['7'], ['7', '7']], ['2', '2']]

i.e each item in the new list printed out as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['1']
['2', '2']
[['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']]
[['7', '7'], ['8'], ['7'], ['1'], ['7', '7']]
[['7', '7'], ['8'], ['7'], ['7', '7']]
['2', '2']

Thanks.

>Solution :

You can use a simple test on the sublists length in a list comprehension:

out = [l[0] if len(l)==1 else l for l in test_list]

output:

[['1'],
 ['2', '2'],
 [['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']],
 [['7', '7'], ['8'], ['7'], ['1'], ['7', '7']],
 [['7', '7'], ['8'], ['7'], ['7', '7']],
 ['2', '2']]

If you really want to print:

for l in test_list:
    print(l[0] if len(l)==1 else l)

['1']
['2', '2']
[['3', '3'], ['4', '4'], ['5', '5'], ['6', '6']]
[['7', '7'], ['8'], ['7'], ['1'], ['7', '7']]
[['7', '7'], ['8'], ['7'], ['7', '7']]
['2', '2']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading