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.



Previous Article
Next Article

Similar Reads

Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Sort Flatten list of list
The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted
7 min read
Python Program To Flatten A Multi-Level Linked List Depth Wise- Set 2
We have discussed flattening of a multi-level linked list where nodes have two pointers down and next. In the previous post, we flattened the linked list level-wise. How to flatten a linked list when we always need to process the down pointer before next at every node. Input: 1 - 2 - 3 - 4 | 7 - 8 - 10 - 12 | | | 9 16 11 | | 14 17 - 18 - 19 - 20 |
4 min read
Python | All Permutations of a string in lexicographical order without using recursion
Write a python program to print all the permutations of a string in lexicographical order. Examples: Input : python Output : hnopty hnopyt hnotpy hnotyp hnoypt ...... ytpnho ytpnoh ytpohn ytponh Input : xyz Output : xyz xzy yxz yzx zxy zyx Method 1: Using the default library itertools function permutations. permutations function will create all the
2 min read
Python | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print (
5 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() + extend() The combination of a
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Practice Tags :
three90RightbarBannerImg