HomePythonPython Program to Flatten a List without using Recursion

Python Program to Flatten a List without using Recursion


Flattening a nested list means converting a list that contains other lists (and potentially more nested lists) into a single-level list containing all the elements from the original list, while preserving their order. This can be achieved through various methods, and one common approach is using iteration (like loops) without involving recursion.

Problem Statement

Given a nested list containing integers and possibly other nested lists, implement a function in python to flatten the list into a single-level list without using recursion. The order of elements should be preserved.

Python Program to Flatten a List without using Recursion

def flatten_list(nested_list):
    flattened_list = []
    stack = [nested_list]

    while stack:
        current = stack.pop()
        if isinstance(current, list):
            stack.extend(current)
        else:
            flattened_list.append(current)

    return flattened_list

# Example usage
nested_list = [1, [2, 3], [4, [5, 6]], 7]
result = flatten_list(nested_list)
print(result)  # Output: [1, 2, 3, 4, 5, 6, 7]

How it Works

  1. The function flatten_list(nested_list) takes a nested list as input.
  2. Inside the function, we initialize an empty list called flattened_list to store the flattened elements.
  3. We also initialize a stack, which will be used to process the nested structure iteratively. We start by pushing the nested_list onto the stack.
  4. We enter a loop that continues until the stack is empty.
  5. In each iteration of the loop, we pop an element current from the stack.
  6. We check whether the current element is a list using the isinstance() function. If it is a list, we extend the stack with the elements of this list. This essentially “unpacks” the nested structure one level at a time.
  7. If the current element is not a list, it’s an integer or a non-list element. In this case, we add it to the flattened_list.
  8. We repeat the process, iteratively popping elements from the stack, extending the stack with lists, and adding non-list elements to the flattened_list, until the stack is empty.
  9. Once the loop completes, all elements have been processed and added to the flattened_list.
  10. We return the flattened_list, which now contains all the elements from the original nested list, flattened into a single-level list while preserving their order.

Input/ Output

Leave a Reply

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...