-1

I'm trying to create a while loop for my code. The idea is not to use so many "for" loops to put it into a function

int_list = [[[1]],2,[[[[3]]]]]

for i in int_list:
    if type(i) != list:
        list_of_lists.append(i)
    else:
        for a in i:
            if type(a) != list:
                list_of_lists.append(a)
            else:
                for j in a:
                    if type(j) != list:
                        list_of_lists.append(j)
                    else:
                        for h in j:
                            if type(h) != list:
                                list_of_lists.append(h)
                            else:
                                for r in h:
                                    if type(r) != list:
                                        list_of_lists.append(r)

Expected Output

list_of_lists = [1,2,3]

2 Answers2

0

One way to reduce for loop is to create a recursive function.

The function recursively calls itself on that sublist(i) by passing it as an argument to helper(). The resulting list is then extended to the result list using the extend() method.

If it's instance is not a list. it runs else part. appending value into the lis

Code:

def helper(lis):
    res=[]
    for i in lis:
        if isinstance(i, list):
            res.extend(helper(i))
        else:
            res.append(i)
    return res

int_list=[[[1]], 2, [[[[3]]]]]
list_of_lists=helper(int_list)
print(list_of_lists)

Output:

[1,2,3]
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
0

A recursive function is the ideal way to flatten a list like this. If you really want to do it in a single while loop, though, it is possible, by creating a stack to help you keep track of where you are in each sublist.

This happens automatically for you when you define and call a recursive function; every call to the function puts all the function's local variables onto a "stack", just like the code below puts the current list and index onto a list called stack every time a new sublist is discovered.

int_list = [[[1]],2,[[[[3]]]]]

flat_list = []
stack = []
i = 0
while True:
    if i >= len(int_list):
        # We're at the end of this sublist,
        # so go back to the stack to pick up where we left off.
        if not stack:
            break  # all done!
        int_list, i = stack.pop()
    elif isinstance(int_list[i], list):
        # Keep track of the current list and the next item
        # for us to look at, and then start looking at this sublist.
        stack.append((int_list, i+1))
        int_list, i = int_list[i], 0
    else:
        # We found a scalar item!  Add it to the flat list.
        flat_list.append(int_list[i])
        i += 1

assert flat_list == [1, 2, 3]
Samwise
  • 68,105
  • 3
  • 30
  • 44