This is a Python Program to flatten a nested list using recursion.
The program takes a nested list and flattens it using recursion.
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.
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))
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.
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.
- Check Information Technology Books
- Apply for Programming Internship
- Apply for Python Internship
- Practice Programming MCQs
- Check Python Books