Menu

gitpiper

deep_flatten python Code Snippet in 2024

listrecursionintermediate

Last Updated: 19 April 2024

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])
deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5]

python snippet similar to deep_flatten For You in April 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️