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.
Python code
17 linesdef 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
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
- Use a list comprehension: `[x for sub in nested_list for x in (sub if isinstance(sub, list) else [sub])]`.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.