
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to Flatten a Nested List using Recursion
When it is required to flatten a given nested list using recursion technique, simple indexing, and the ‘isinstance’ method can be used along with recursion.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Example
Below is a demonstration for the same −
def flatten_list(my_list): if my_list == []: return my_list if isinstance(my_list[0], list): return flatten_list(my_list[0]) + flatten_list(my_list[1:]) return my_list[:1] + flatten_list(my_list[1:]) my_list = [[1,2],[3,4], [90, 11], [56, 78], [[34,56]]] print("The list is :") print(my_list) print("The list after flattening is : ") print(flatten_list(my_list))
Output
The list is : [[1, 2], [3, 4], [90, 11], [56, 78], [[34, 56]]] The list after flattening is : [1, 2, 3, 4, 90, 11, 56, 78, 34, 56]
Explanation
- A method named ‘flatten_list’ is defined, that takes a list as parameter.
- It checks to see the data type of the first element in the list.
- If it matches to a list, then, the first element along with the second element to last element is concatenated and displayed.
- This results in a nested list being flattened.
- Otherwise, the first element is left out, and the list is first reversed and the normal list is combined, and returned as output.
- Outside the function, a nested list is defined, and is displayed on the console.
- The method is called by passing the list as parameter.
- The output is displayed on the console.
- Related Articles
- Python Program to Flatten a List without using Recursion
- Python program to Flatten Nested List to Tuple List
- Flatten Nested List Iterator in Python
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Function to flatten array of multiple nested arrays without recursion in JavaScript
- Python Program to Find the Length of a List Using Recursion
- Python - Ways to flatten a 2D list
- Python Program to Display all the Nodes in a Linked List using Recursion
- Python Program to Print the Alternate Nodes in a Linked List using Recursion
- How to flatten a list using LINQ C#?
- How to flatten a shallow list in Python?
- Python Program to Find the Length of the Linked List using Recursion
- Python Program to Reverse a String Using Recursion
- Python Program to Reverse a Stack using Recursion
- Python Program to Display the Nodes of a Linked List in Reverse using Recursion

Advertisements