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

Your email address will not be published. Required fields are marked *

You May Also Like

In this python tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...