Python Program to Flatten a List without using Recursion

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

Problem Description

The program takes a nested list and flattens the nested list without using recursion.

Problem Solution

1. A variable must be initialized with a nested list.
2. Use a lambda function and map() to map the flatten function to each element in the nested list to flatten the list.
3. Print the flattened list.
4. Exit.

Program/Source Code

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

a=[[1,[[2]],[[[3]]]],[[4],5]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print(flatten(a))
Program Explanation

1. A variable is initialized with a nested list.
2. Using a lambda function and map(), the function flatten is mapped to each element in the nested list to flatten the list.
3. The flattened list is then printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
[1, 2, 3, 4, 5]

Sanfoundry Global Education & Learning Series – Python Programs.

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

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

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.