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 do I flatten a list that contains nested lists of varying "nestedness" levels?

The list in question may look like: [1, [1, 2], [1, [2, 3]], [1, [2, [3, 4]]]]. The output list that I want would take that list of lists and flatten it to [1, 1, 2, 1, 2, 3, 1, 2, 3, 4].

I thought of using a while loop with the condition to check if there are any elements in the list that are of type list and flattening them but am having trouble coming up with an algorithm that takes care of that. Is there a way to perform what I want?

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

>Solution :

def flatten(xs): 
    # Initialize list for this layer 
    flat_list = []
    for x in xs: 
        # If it's a list, recurse down and return the interior list
        if isinstance(x, list): 
            flat_list += flatten(x)
        # Otherwise, add to this layer's list
        else: 
            flat_list.append(x) 
    return flat_list

x = [1, [1, 2], [1, [2, 3]], [1, [2, [3, 4]]]]
print(flatten(x)) 
# [1, 1, 2, 1, 2, 3, 1, 2, 3, 4]

Here’s a simple solution that uses recursion to progressively flatten the list. Each time we encounter an interior list, we flatten it, and append it to that layer’s list.

Here are some other answers, found in the link from the linked question: Flatten an irregular (arbitrarily nested) list of lists

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