0

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?

Sean
  • 2,890
  • 8
  • 36
  • 78
  • 1
    @accdias Unfortunately it doesn't because the solutions posted there assume that _all_ of the elements are lists and also because it would only take care of the outermost list. – Sean Dec 06 '22 at 03:16
  • Duplicate of: https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists – Al.Sal Dec 06 '22 at 03:41

1 Answers1

1
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

Al.Sal
  • 984
  • 8
  • 19
  • 1
    Since your answer is based on another SO question, the best course of action would be posting a comment stating the question is a [duplicate](https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists). – accdias Dec 06 '22 at 03:30
  • Got it, I already made the post then was looking around and found the dupe. – Al.Sal Dec 06 '22 at 03:40