Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How to Flatten a Nested List in Python

Learn how to flatten nested lists in Python using list comprehensions, itertools.chain, recursion, generators, and an iterative stack. Compare readability, memory use, and when each approach is appropriate.

~6 min readPython
#list flattening#recursion#itertools#list comprehension
Illustration of a nested list structure being flattened into a single list in Python, showing layers of brackets collapsing into a linear sequence.

When working with data in Python, you often encounter nested lists—lists that contain other lists as elements. The operation of converting such a structure into a single flat list is known as flattening. The right way to flatten a nested list depends on the depth of nesting, the types of elements, and whether you need to preserve order or handle deeply nested structures. This article walks through the common approaches, their tradeoffs, and the situations where each is most appropriate.

The Basic Case: Flattening One Level of Nesting

If your list contains only one level of nesting—for example, [[1, 2], [3, 4]]—the simplest solution is a list comprehension that iterates over each sublist and then over each item inside it.

python
nested = [[1, 2], [3, 4]] flat = [item for sublist in nested for item in sublist] print(flat) # [1, 2, 3, 4]

The comprehension reads as: for each sublist in nested, for each item in sublist, collect item. This is concise and fast for a single level when every element of the outer list is itself iterable. It does not handle a mix of values and sublists like [1, [2, 3], 4]: Python would try to iterate over the integer 1 and raise TypeError. If your data has that shape, use one of the recursive approaches below.

For the same one-level case, the itertools module provides chain.from_iterable, which is often slightly more readable when you already use itertools elsewhere.

python
from itertools import chain nested = [[1, 2], [3, 4]] flat = list(chain.from_iterable(nested)) print(flat) # [1, 2, 3, 4]

chain.from_iterable also requires every element of the outer list to be iterable. Both approaches produce the same result for the standard one-level case, but the list comprehension is more explicit about the iteration order. In CPython, chain.from_iterable can be slightly faster because the iteration is delegated to C code, but the difference is rarely significant unless you are flattening millions of sublists.

Flattening Deeper or Variably Nested Lists

When the nesting depth is unknown or can vary, a one-level approach fails. For example, [1, [2, [3, [4]]]] can be handled with a recursive function that traverses the list and extends a result list whenever it encounters a non-list element.

python
def flatten_recursive(nested): result = [] for item in nested: if isinstance(item, list): result.extend(flatten_recursive(item)) else: result.append(item) return result print(flatten_recursive([1, [2, [3, [4]]]])) # [1, 2, 3, 4]

The function checks each element. If it is a list, it recurses and extends the result with the flattened sublist; otherwise, it appends the element directly. This works for any depth up to Python's recursion limit (default 1000), but it creates a new result list at each recursion level. For deeply nested structures, you may hit RecursionError.

A generator-based version avoids building intermediate lists and yields elements lazily, which is more memory-efficient for large inputs.

python
def flatten_generator(nested): for item in nested: if isinstance(item, list): yield from flatten_generator(item) else: yield item flat = list(flatten_generator([1, [2, [3, [4]]]])) print(flat) # [1, 2, 3, 4]

yield from delegates the iteration to the recursive call, so the generator only produces one element at a time. This is the preferred approach when you need to process a large flattened sequence without holding all values in memory at once.

Handling Mixed Types and Non-List Elements

The recursive examples above treat any list as a container to flatten, and any other object as a leaf. This works well when your data is homogeneous—all leaves are numbers or strings. If your data stores nested values in tuples as well, you need a broader container check.

For example, the recursive functions above flatten only list values and leave tuples intact. If you need to flatten tuples as well, change the check to isinstance(item, (list, tuple)).

If you want to flatten any iterable except strings, use a broader check. Strings are iterable, but usually you want to treat them as atomic values. collections.abc.Iterable provides a general test:

python
from collections.abc import Iterable def flatten_except_strings(nested): for item in nested: if isinstance(item, Iterable) and not isinstance(item, str): yield from flatten_except_strings(item) else: yield item

This version treats strings as leaves, which is usually the desired behavior. Be aware that a dictionary is also iterable, so this function would flatten dictionary keys; adjust the container check if your data can include dicts or other iterable non-sequence types. The key is to define exactly what counts as a "container" for your specific data schema.

Performance and Memory Considerations

The choice between recursion and iteration affects both speed and memory usage. For a single level of nesting, both the list comprehension and chain.from_iterable are efficient and do not recurse; chain.from_iterable delegates iteration to C, while the list comprehension is concise and generally fast enough. For deeper structures, the recursive generator is generally more memory-friendly than the recursive list-returning function, because it does not allocate a new list at each level. However, recursion still consumes stack frames, and the recursion depth limit can become a bottleneck for pathological inputs.

If you need to flatten a list that is thousands of levels deep, recursion will fail. In that case, an iterative approach using an explicit stack is safer, though more verbose.

python
def flatten_iterative(nested): stack = list(reversed(nested)) result = [] while stack: item = stack.pop() if isinstance(item, list): stack.extend(reversed(item)) else: result.append(item) return result

This uses a stack to avoid recursion entirely. It processes elements in the same order as the recursive version because we reverse the list before pushing onto the stack. The memory usage depends on the number of items waiting on the stack; it avoids Python call-stack overhead, but in the worst case the stack can hold many input elements. This is the most robust option if you know the input can be extremely deep, but it is less readable and should only be used when recursion depth is a real concern.

Choosing the Right Approach for Your Use Case

ApproachDepth LimitMemory ProfileReadabilityBest For
List comprehensionOne levelCreates full result listHighSimple, known depth
itertools.chainOne levelIterator; list() materializesMediumOne-level flattening in existing code
Recursive list builderPython recursion limitIntermediate listsMediumModerate depth, small data
Recursive generatorPython recursion limitLazy, low peak memoryMediumLarge data, streaming processing
Iterative with stackNo recursion limitStack memory depends on inputLowVery deep nesting, production safety

Use a one-level method when the structure is always exactly one level deep, such as [[1, 2], [3, 4]]. Use the recursive generator when nesting depth can vary but the data size is manageable and Python's recursion limit is not a concern. Use the iterative stack when you must avoid RecursionError even for very deep input. The generator is often the best balance of clarity and memory efficiency for most real-world data, such as JSON payloads that may nest a few levels but not hundreds.

Edge Cases and Common Pitfalls

Several edge cases can trip up a naive flattening implementation. First, empty lists: both recursive and iterative versions handle them correctly because they simply contribute no elements. Second, lists containing None or other falsy values: the isinstance check does not depend on truthiness, so None is treated as a leaf, which is usually correct. Third, cycles: if a list contains a reference to itself, any recursive or iterative flattening will loop indefinitely. There is no built-in cycle detection, so you must either guarantee acyclic input or track the containers currently on the recursion path. A global set of object IDs is not enough, because the same list can appear in two different branches and should be flattened each time.

Another common mistake is using isinstance(item, list) when the data contains tuples or other sequence types that should be flattened. Conversely, using a broad check like isinstance(item, Iterable) without excluding strings will treat strings as containers, splitting them into characters. Always test your flattening function with a sample that includes the actual types you expect, including any unusual but valid elements like dictionaries or custom objects.

Finally, consider whether you need to preserve the original order. All the methods shown here preserve the left-to-right depth-first order, which is what most applications expect. If you need a different ordering, such as breadth-first, you would need to adjust the algorithm accordingly. Flattening is a fundamental operation, and choosing the right implementation now can save you from subtle bugs later when your data grows or changes shape.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.