Python: Perform a deep flattens a list
Python List: Exercise - 255 with Solution
Write a Python program to perform a deep flattening of a list.
- Use recursion.
- Use isinstance() with collections.abc.Iterable to check if an element is iterable.
- If it is iterable, apply deep_flatten() recursively, otherwise return [lst].
Sample Solution:
Python Code:
from collections.abc import Iterable
def deep_flatten(lst):
return ([a for i in lst for a in
deep_flatten(i)] if isinstance(lst, Iterable) else [lst])
nums = [1, [2], [[3], [4], 5], 6]
print("Original list elements:")
print(nums)
print()
print("Deep flatten the said list:")
print(deep_flatten(nums))
nums = [[[1, 2, 3], [4, 5]], 6]
print("\nOriginal list elements:")
print(nums)
print()
print("Deep flatten the said list:")
print(deep_flatten(nums))
Sample Output:
Original list elements: [1, [2], [[3], [4], 5], 6] Deep flatten the said list: [1, 2, 3, 4, 5, 6] Original list elements: [[[1, 2, 3], [4, 5]], 6] Deep flatten the said list: [1, 2, 3, 4, 5, 6]
Flowchart:

Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to get the weighted average of two or more numbers.
Next: Write a Python program to get the powerset of a given iterable.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Capitalizes the first letter of a string:
Example:
def tips_capitalize(s, lower_rest=False): return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:]) print(tips_capitalize('pythonTips')) print(tips_capitalize('pythonTips', True))
Output:
PythonTips Pythontips
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook