Neural Mastery
← Practice
Flatten an Arbitrarily Nested Listeasy

Flatten an Arbitrarily Nested List

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Flatten an arbitrarily nested hierarchy of lists into a single flat list -- a foundational recursive pattern common in parsing hierarchical JSON responses and nested token structures.

Related Skills

Task

Implement flatten_nested_list(nested): recursively traverse nested and return a flat list containing all leaf (non-list) elements in their original order. Empty lists should be ignored. Return an empty list if nested contains no leaf items.

Function Signature

flatten_nested_list(nested: list) -> list

Examples

Example 1: Irregular Nested Structure
Input: nested = [1, [2, [3, 4], 5], [6], 7]
Output: [1, 2, 3, 4, 5, 6, 7]
Example 2: Already Flat List
Input: nested = [10, 20, 30]
Output: [10, 20, 30]

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must handle arbitrary nesting depth (e.g. lists within lists within lists).
  • Non-list elements should remain intact and ordered.
Python3Saved ✓
def flatten_nested_list(nested: list) -> list:
"""Flatten an arbitrarily nested list of items into a 1D list.

Preserves the relative ordering of all leaf items. Handles empty
sublists and arbitrary nesting depth."""
# Your implementation here
pass

Case 1: Irregular Nested Structure
Input: nested = [1, [2, [3, 4], 5], [6], 7]
Expected: [1, 2, 3, 4, 5, 6, 7]
Case 2: Already Flat List
Input: nested = [10, 20, 30]
Expected: [10, 20, 30]