How to Flatten a List Without Using Recursion in Python

In this tutorial, we will learn how to program "How to Flatten a List Without Using Recursion in Python". The objective is to flatten a nested list into a single-level list without using recursion. This tutorial will guide you step by step through methods for flattening a list efficiently. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of flattening a list without using recursion. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. import ast  # for safely parsing list input
  2.  
  3. def flatten_list(nested):
  4.     flatten = lambda l: sum(map(flatten, l), []) if isinstance(l, list) else [l]
  5.     return flatten(nested)
  6.  
  7. while True:
  8.     print("\n============ Flatten a List Without Using Recursion ============\n")
  9.  
  10.     # Ask user for a list
  11.     user_input = input("Enter a nested list (example: [1, [2, [3, 4]], 5]): ")
  12.  
  13.     try:
  14.         # Convert string to actual Python list safely
  15.         nested_list = ast.literal_eval(user_input)
  16.  
  17.         if not isinstance(nested_list, list):
  18.             print("❌ Error: Input must be a list!")
  19.             continue
  20.  
  21.         print("\nFlattened List:")
  22.         print(flatten_list(nested_list))
  23.  
  24.     except Exception as e:
  25.         print("❌ Invalid input. Make sure it's a valid list.")
  26.         continue
  27.  
  28.     # Try again?
  29.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  30.  
  31.     if opt == "no":
  32.         print("Exiting program...")
  33.         break
  34.     elif opt != "yes":
  35.         print("Invalid choice. Exiting program...")
  36.         break

This program flattens a nested list into a single-level list without using recursion. It prompts the user to input a nested list, safely parses it using `ast.literal_eval`, and then uses a lambda function with `map` and `sum` to produce a flattened version. The program repeatedly allows the user to enter new lists or exit.

Output:

There you have it we successfully created How to Flatten a List Without Using Recursion in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials