Python: Perform a deep flattens a list
Python List: Exercise - 255 with Solution
Write a Python program to perform a deep flattens 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].
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, , [, , 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))
Original list elements: [1, , [, , 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]
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.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Big Number Readability:
you can separate zeros with underscore (_)
print(2_000_000) print(2_000_000 +1)
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework