Flattening unknown nesting level of list using looping in Python

Question:

I need to solve the below problem using looping.

Statement

Your input is a list of lists with unknown nesting level. Could be like:

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

Your challenge is to reshape it into a single list like that:

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

My code is :

import json

data = json.loads(input())
#WRITE YOUR CODE HERE 
list_data = list(data) 
flat_list = [item for items in list_data for item in items] 
print(flat_list)

TypeError: ‘int’ object is not iterable

Asked By: Albina Hakobyan

||

Answers:

Try recursive approach:

lst = [[1, 2],[3,[4, 5],],6,7]

def flat_list(lst, res):
    for l in lst:
        if isinstance(l, list):
            flat_list(l, res)
        else:
            res.append(l)
            
result = []
flat_list(lst, result)
print(result)

Output:

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

Update: (use looping without recursive approach)

lst = [[1, 2],[3,[4, 5],],6,7]

res = []
for l in lst:
    tmp = [l]
    while tmp != []:
        for i in tmp:
            if isinstance(i, list):
                for j in i:
                    tmp.append(j)
            else:
                res.append(i)
            tmp = tmp[1:]
print(res)
# [1, 2, 3, 4, 5, 6, 7]
Answered By: I'mahdi

Here is a stack-based approach:

lst = [[1, 2], [3, [4, 5], ], 6, 7]

stack = lst[::-1]
res = []

while stack:
    item = stack.pop()
    if isinstance(item, list):
        for x in item[::-1]:
            stack.append(x)
    else:
        res.append(item)

print(res)
Answered By: Tom McLean
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.