How to Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

17 lines
Python 3.9+
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mixed nesting depth
    data = [1, [2, 3], 4, [5, [6, 7]], 8]
    result = flatten_one_level(data)
    print("Original:", data)
    print("Flattened one level:", result)
    print("Type preserved:", all(not isinstance(x, list) or len(x) <= 1 for x in result))

Output

stdout
Original: [1, [2, 3], 4, [5, [6, 7]], 8]
Flattened one level: [1, 2, 3, 4, 5, [6, 7], 8]
Type preserved: True

How it works

The function loops through each item in the input list. If isinstance(item, list) is true, flattened.extend(item) adds all elements of that sublist as individual items at the top level. Non-list items are appended unchanged, preserving their original type. Because the loop only goes one level deep, any list found inside a sublist stays nested. The example verifies that no remaining element is a list with more than one item, confirming only one level was flattened.

Common mistakes

  • Using `append` instead of `extend` for sublists, which adds the list itself rather than its elements.
  • Recursively flattening instead of stopping at one level, which changes deeper structure.
  • Forgetting that tuples are not lists, so they won't be flattened by this function.

Variations

  1. Use a list comprehension: `[x for sub in nested_list for x in (sub if isinstance(sub, list) else [sub])]`.
  2. Use `itertools.chain.from_iterable` after wrapping non-list items: `list(chain.from_iterable((x if isinstance(x, list) else [x]) for x in nested_list))`.

Real-world use cases

  • Normalizing rows from a CSV import where some fields are already lists that need to be inlined once.
  • Preparing data for a table by flattening group headers that contain multiple values while keeping deeper groups intact.
  • Combining multiple query result groups into a single flat list for further processing in an ETL pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.