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:
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 :
- Define a function named flatten that takes a list lst as an input.
- Initialize an empty list result that will store the flattened list.
- Use a loop to iterate through each element x of the input list.
- Check if the current element x is a list or not using isinstance(x, list).
- 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)).
- If the current element x is not a list, append it directly to the result list using result.append(x).
- Return the flattened list result.
- Create a list l that contains nested lists.
- Call the flatten function on the list l and store the flattened list in a variable ans using ans = flatten(l).
- 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.
Similar Reads
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python.Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a sin
3 min read
Create List of Numbers with Given Range - Python
The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8
3 min read
Python - Add List Items
Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples:Add a Single Item Using append()append() method adds one item to the end of the li
3 min read
How to add Elements to a List in Python
In Python, lists are dynamic which means that they allow further adding elements unlike many other languages. In this article, we are going to explore different methods to add elements in a list. For example, let's add an element in the list using append() method:Pythona = [1, 2, 3] a.append(4) prin
2 min read
Python List Access
Python - Access List Item
Whether we are working with numbers, strings or other data types, lists provide a versatile way to organize and manipulate data. But how to access specific items in a list? This article will guide you through various methods of accessing list items in Python.Accessing List Items by IndexIn Python, l
3 min read
Accessing index and value in Python list
We are given a list, and our task is to access both the index and value of each element in the list using Python. For example, using enumerate(list) in a loop like for index, value in enumerate(list) allows us to access both the index and the value together.Using enumerate() enumerate() is preferred
2 min read
Accessing all elements at given list of indexes-Python
Sometimes, you may have a list of data and a separate list of indexes and the goal is to extract only the elements at those specific positions. For example, given a list [10, 20, 30, 40, 50] and a list of indexes [1, 3, 4], you want to retrieve [20, 40, 50] the values at those index positions in the
2 min read
Python List Slicing
Python list slicing is fundamental concept that let us easily access specific elements in a list. In this article, weâll learn the syntax and how to use both positive and negative indexing for slicing with examples.Example: Get the items from a list starting at position 1 and ending at position 4 (e
4 min read
List Iteration Operations
Iterate over a list in Python
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
3 min read
How to iterate through a nested List in Python?
A nested list is a list that contains other lists. Working with nested lists can seem tricky at first but it becomes easy once we understand how to iterate through them. This is the easiest way to loop through a nested list. We can use a for loop to access each sublist in the main list, and then use
3 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over
4 min read
Iterate Over a List of Lists in Python
We are given a list that contains multiple sublists, and our task is to iterate over each of these sublists and access their elements. For example, if we have a list like this: [[1, 2], [3, 4], [5, 6]], then we need to loop through each sublist and access elements like 1, 2, 3, and so on. Using Nest
2 min read
Python List Search Operations
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it. Let's explore different methods to find the length of
2 min read
Python | Find elements of a list by indices
Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2. Examples: Input : lst1 = [10, 20, 30, 40, 50] lst2 = [0, 2, 4] Output : [10, 30, 50] Explanation: Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. Input : l
5 min read
Python program to find String in a List
Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python.ExampleMake a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we f
2 min read
Python List Remove Operations
Python - Remove List Item
Removing List Item can be achieved using several built-in methods that provide flexibility in how you remove list items. In this article, we'll explore the different ways to remove list items in Python.Removing Item by Value with remove()The remove() method allows us to remove the first occurrence o
3 min read
How to Remove Item from a List in Python
Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the element or index.The simplest way to remove an element from a list by i
3 min read
Python | Remove given element from the list
Given a list, write a Python program to remove the given element (list may have duplicates) from the given list. There are multiple ways we can do this task in Python. Let's see some of the Pythonic ways to do this task. Example: Input: [1, 8, 4, 9, 2] Output: [1, 8, 4, 2] Explanation: The Element 9
7 min read
Ways to remove particular List element in Python
There are times when we need to remove specific elements from a list, whether itâs filtering out unwanted data, deleting items by their value or index or cleaning up lists based on conditions. In this article, weâll explore different methods to remove elements from a list.Using List ComprehensionLis
2 min read
Remove Multiple Elements from List in Python
In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list.Pythona = [10, 20, 30, 40, 50, 60, 70] # Elements to remove remove = [20, 40,
2 min read
Python List Concatenation Operations
Python - Concatenate two lists element-wise
In Python, concatenating two lists element-wise means merging their elements in pairs. This is useful when we need to combine data from two lists into one just like joining first names and last names to create full names. zip() function is one of the most efficient ways to combine two lists element-
3 min read
Merge Two Lists in Python
Python provides several approaches to merge two lists. In this article, we will explore different methods to merge lists with their use cases. The simplest way to merge two lists is by using the + operator. Let's take an example to merge two lists using + operator.Pythona = [1, 2, 3] b = [4, 5, 6] #
4 min read
Concatenate two list of lists Row-wise-Python
The task of concatenate two lists of lists row-wise, meaning we merge corresponding sublists into a single sublist. For example, given a = [[4, 3], [1, 2]] and b = [[7, 5], [9, 6]], we pair elements at the same index: [4, 3] from a is combined with [7, 5] from b, resulting in [4, 3, 7, 5], and [1, 2
3 min read
Python program to concatenate every elements across lists
Given 2 lists, perform concatenations of all strings with each other across list. Input : test_list1 = ["gfg", "is", "best"], test_list2 = ["love", "CS"] Output : ['gfg love', 'gfg CS', 'is love', 'is CS', 'best love', 'best CS'] Explanation : All strings are coupled with one another. Input : test_l
4 min read
Concatenate all Elements of a List into a String - Python
We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day".Using str.join()str.join()
2 min read
Concatenate All Records - Python
The task of concatenating all records in Python involves combining elements from a list, typically strings, into a single unified string. The goal is to concatenate each individual element, ensuring that the result is a continuous string without spaces or delimiters, unless specified. For example, g
3 min read
Python - Merge list elements
Merging list elements is a common task in Python. Each method has its own strengths and the choice of method depends on the complexity of the task. This is the simplest and most straightforward method to merge elements. We can slice the list and use string concatenation to combine elements.Pythona =
2 min read
Python | Concatenate N consecutive elements in String list
Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let's discuss certain ways in which this task can be performed. Method #1: Using format() + zip() + i
8 min read
Python | Merge two lists alternatively
Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length. Examples: Input : lst1 = [1, 2, 3] lst2 = ['a', 'b', 'c'] Output : [1, 'a', 2, 'b', 3, 'c'] Input : lst1 = ['name', 'alice', 'bob'] lst2 = ['marks', 87, 56] Ou
4 min read
Python - Union of two or more Lists
The union of two or more lists combines all elements ensuring no duplicates if specified. In this article we will explore various methods to get a union of two lists.Using set.union (Most Efficient for Uniqueness)The union() method ensures that the resulting list contains unique elements. Here we co
2 min read