How do I flatten a list that contains nested lists of varying "nestedness" levels?

Question:

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?

Asked By: Sean

||

Answers:

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

Answered By: Al.Sal
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.