w3resource

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].

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:

Flowchart: Perform a deep flattens a list.

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 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)

Output:

2000000
2000001