Python Program to Flatten a List without using Recursion
Last Updated :
07 Apr, 2023
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list can be a number or a list. It needs to be converted to a list where each element in the list is only a number.
Examples:
Input: [1,2,[3,4,[5,6],7],[[[8,9],10]],[11,[12,13]]]
Output: [1,2,3,4,5,6,7,8,9,11,12,13]
Input: [1, [2, 3]]
Output: [1, 2, 3]
Method 1: Using stack
Approach:
- Initialization: Push the main list in a stack
- Make an empty list to store the final result (result variable)
- Loop till the stack is not empty
- Pop the last added element of the stack and store it (current variable)
- If the popped element is a list then pushing all the elements of that list in the stack
- If the popped element is not a list, append that element to the result
- Reverse the result list to get the final output in the original list’s order
Implementation: