Open In App

Python Program to Flatten a List without using Recursion

Last Updated : 07 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
    1. Pop the last added element of the stack and store it (current variable)
    2. If the popped element is a list then pushing all the elements of that list in the stack
    3. 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:

Python3




# Input list
l = [1, 2, [3, 4, [5, 6], 7],
     [[[8, 9], 10]],
     [11, [12, 13]]]
 
# Function to flatten the list
 
 
def flatten(input_list):
    # Final list to be returned
    result = []
 
    # Creating stack and adding
    # all elements into it
    stack = [input_list]
 
    # Iterate stack till it
    # does not get empty
    while stack:
 
        # Get the last element of the stack
        current = stack.pop(-1)
 
        # If the last element is a list,
        # add all the elements of that list in stack
        if isinstance(current, list):
            stack.extend(current)
 
        # Else add that element in the result
        else:
            result.append(current)
 
    # Reverse the result to get the
    # list in original order
    result.reverse()
 
    return result
 
 
# output list
ans = flatten(l)
print(ans)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(m), where m is the maximum depth of nested lists in the input list.  determines the maximum size of the stack.

Method 2: Using libraries

The package iteration_utilities can also be used to flatten a list.

Python3




from iteration_utilities import deepflatten
 
l = [1, 2, [3, 4, [5, 6], 7],
     [[[8, 9], 10]], [11, [12, 13]]]
 
ans = list(deepflatten(l))
print(ans)


Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: “Recursive Function to Flatten a Nested List”

This program defines a recursive function flatten that takes a nested list as input and returns a flattened list. The function recursively flattens any sublists within the input list by extending the result list with their elements, and returns the final flattened list. 

step by step approach :

  1. Define a function named flatten that takes a list lst as an input.
  2. Initialize an empty list result that will store the flattened list.
  3. Use a loop to iterate through each element x of the input list.
  4. Check if the current element x is a list or not using isinstance(x, list).
  5. If the current element x is a list, recursively call the flatten function on the list x using flatten(x), and extend the resulting flattened list to result using result.extend(flatten(x)).
  6. If the current element x is not a list, append it directly to the result list using result.append(x).
  7. Return the flattened list result.
  8. Create a list l that contains nested lists.
  9. Call the flatten function on the list l and store the flattened list in a variable ans using ans = flatten(l).
  10. Print the flattened list ans using print(ans).

Python3




def flatten(lst):
    result = []
    for x in lst:
        if isinstance(x, list):
            result.extend(flatten(x))
        else:
            result.append(x)
    return result
 
 
l = [1, 2, [3, 4, [5, 6], 7], [[[8, 9], 10]], [11, [12, 13]]]
ans = flatten(l)
print(ans)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time complexity: O(N), where N is the total number of elements in the nested list lst. 
Auxiliary space: O(N), where N is the total number of elements in the nested list lst.

Method 4:  using a generator function.

This implementation uses the yield keyword to create a generator function that recursively flattens the list. The yield from expression is used to delegate the flattening of nested lists to the same generator function. The result is a flattened list that is generated lazily as the generator function is consumed using the list() function

Python3




def flatten(lst):
    for x in lst:
        if isinstance(x, list):
            yield from flatten(x)
        else:
            yield x
 
 
l = [1, 2, [3, 4, [5, 6], 7], [[[8, 9], 10]], [11, [12, 13]]]
ans = list(flatten(l))
print(ans)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time complexity: O(n), where n is the total number of elements in the nested list. 
Auxiliary space: O(d), where d is the maximum depth of the nested list.

Method 5: Iterative approach

The function first creates an empty result list and a stack list containing the input lst. Then, it enters a loop that continues until the stack is empty. Within the loop, it pops the last element from the stack and checks if it is a list or not using isinstance(). If it is a list, the function reverses it and pushes each element onto the stack. If it is not a list, it appends the element to the result list. The loop continues until all elements have been processed and the stack is empty. Finally, the result list is returned.

Step 1: Create an empty list to store the flattened elements.
Step 2: Create an empty stack to hold the list of elements to be processed.
Step 3: Push the given list onto the stack.
Step 4: While the stack is not empty, do the following:

#Pop the top element from the stack.
#If the popped element is a list, push each of its elements onto the stack in reverse order.
#If the popped element is not a list, append it to the result list.
Step 5: Return the result list.

Python3




def flatten(lst):
    result = []
    stack = [lst]
 
    while stack:
        curr = stack.pop()
 
        if isinstance(curr, list):
            for elem in reversed(curr):
                stack.append(elem)
        else:
            result.append(curr)
 
    return result
 
 
l = [1, 2, [3, 4, [5, 6], 7], [[[8, 9], 10]], [11, [12, 13]]]
ans = flatten(l)
print(ans)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time complexity: The time complexity of the iterative approach is O(n), where n is the total number of elements in the input nested list. 

Auxiliary space: The auxiliary space complexity of the iterative approach is also O(n), where n is the total number of elements in the input nested list.

Method 6: Using List Comprehension and Recursion

  • Step 1: Define the flatten function that takes a nested list as input.
  • Step 2: Create an empty result list that will store the flattened list.
  • Step 3: Use a list comprehension to iterate over the elements of the input list.
  • Step 4: Check if the current element is a list or not. If it is a list, call the flatten function recursively on the element and extend the result to the final result list. If it is not a list, append the element to the final result list.
  • Step 5: Return the final result list.

Python3




def flatten(lst):
    result = []
    for x in lst:
        result.extend(flatten(x) if isinstance(x, list) else [x])
    return result
 
 
l = [1, 2, [3, 4, [5, 6], 7], [[[8, 9], 10]], [11, [12, 13]]]
ans = flatten(l)
print(ans)


Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Time complexity: O(n), where n is the total number of elements in the input list.
Auxiliary space: O(n), where n is the total number of elements in the input list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads