Python Program to Flatten a Nested List using Recursion

This is a Python Program to flatten a nested list using recursion.

Problem Description

The program takes a nested list and flattens it using recursion.

Problem Solution

1. Initialize a variable to a nested list.
2. Pass the list as an argument to a recursive function to flatten the list.
3. In the function, if the list is empty, return the list.
4. Otherwise call the function is recursively with the sublists as the parameters until the entire list is flattened.
5. Print the flattened list.
6. Exit.

Program/Source Code

Here is source code of the Python Program to flatten a nested list using recursion. The program output is also shown below.

def flatten(S):
    if S == []:
        return S
    if isinstance(S[0], list):
        return flatten(S[0]) + flatten(S[1:])
    return S[:1] + flatten(S[1:])
s=[[1,2],[3,4]]
print("Flattened list is: ",flatten(s))
Program Explanation

1. A variable is initialized to contain a nested list.
2. The list is passed as an argument to a recursive function to flatten the list.
3. In the function, if the list is empty, the list is returned.
4. Otherwise the function is recursively called with the sublists as the parameters until the entire list is flattened.
5. The flattened list is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Flattened list is:  [1, 2, 3, 4]

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.