SoftwareSideHustles
How-To

How to Flatten a Nested List or Array (One Level or Any Depth)

Flatten a list of lists in Python, nested arrays in JavaScript and nested collections in Java — one level or arbitrarily deep — plus the string-recursion and sum() traps.

By Software Side Hustles Editorial Team · Published · Updated · 4 min read

Quick answer: for one level of nesting, Python [x for sub in nested for x in sub], JavaScript nested.flat(), Java nested.stream().flatMap(List::stream).toList(). For any depth, JavaScript has nested.flat(Infinity); in Python, write a small recursive generator that treats strings as values, not lists.

One level deep: list of lists

python
nested = [[1, 2], [3], [], [4, 5]]
[x for sub in nested for x in sub] # [1, 2, 3, 4, 5]
from itertools import chain
list(chain.from_iterable(nested)) # [1, 2, 3, 4, 5]

The comprehension reads in the same order as nested for loops: "for each sub in nested, for each x in sub, keep x". People often write the two clauses in the wrong order and get NameError: name 'sub' is not defined.

javascript
const nested = [[1, 2], [3], [], [4, 5]];
nested.flat(); // [1, 2, 3, 4, 5]
nested.flatMap((sub) => sub.map((x) => x * 2)); // map and flatten in one pass
java
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3), List.of(), List.of(4, 5));
List<Integer> flat = nested.stream().flatMap(List::stream).toList(); // [1, 2, 3, 4, 5]

C# uses SelectMany: nested.SelectMany(x => x).ToList().

Avoid sum(nested, [])

python
sum(nested, []) # works, but O(n²)

It looks elegant, but each addition creates a new list and copies everything so far. With thousands of sublists it becomes dramatically slower than chain.from_iterable. The same applies to reduce((a, b) => a.concat(b), []) in JavaScript.

Any depth: arbitrarily nested data

javascript
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]

Python has no built-in for this, so use a recursive generator:

python
def flatten(items):
for x in items:
if isinstance(x, (list, tuple)):
yield from flatten(x)
else:
yield x
list(flatten([1, [2, [3, (4, 5)]], "abc"])) # [1, 2, 3, 4, 5, 'abc']

Why not check for "any iterable"?

It is tempting to write if isinstance(x, Iterable) so the function works for sets, generators and more. But a string is iterable, and each character of a string is itself a one-character string — which is also iterable. The function recurses forever and dies with RecursionError: maximum recursion depth exceeded. If you do accept general iterables, exclude str and bytes explicitly:

python
from collections.abc import Iterable
def flatten(items):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x

Dictionaries are iterable too (over their keys), which is rarely what you want; decide whether they count as values.

Iterative flattening for very deep data

Recursion depth is limited — about 1,000 frames by default in Python. Data nested deeper than that (rare, but possible with generated or hostile input) needs an explicit stack:

python
def flatten_iterative(items):
stack = [iter(items)]
while stack:
for x in stack[-1]:
if isinstance(x, (list, tuple)):
stack.append(iter(x))
break
yield x
else:
stack.pop()

The for … else clause runs only when the inner loop finishes without break, meaning the current list is exhausted. This preserves order and handles any depth. See maximum recursion depth and stack overflow for the general technique.

Flattening with NumPy and pandas

For numeric arrays, NumPy flattens in C:

python
import numpy as np
np.array([[1, 2], [3, 4]]).ravel() # array([1, 2, 3, 4]) — a view when possible
np.array([[1, 2], [3, 4]]).flatten() # always a copy

This only works for regular (rectangular) arrays. A ragged list such as [[1, 2], [3]] must be flattened with plain Python. In pandas, df["tags"].explode() turns a column of lists into one row per item.

Flattening a nested dictionary

A related task is turning {"db": {"host": "x", "port": 5432}} into {"db.host": "x", "db.port": 5432} — useful for config files and environment variables:

python
def flatten_dict(d, prefix=""):
out = {}
for k, v in d.items():
key = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
out.update(flatten_dict(v, key))
else:
out[key] = v
return out

pandas offers pd.json_normalize for the same job on JSON records.

Frequently asked questions

How do I flatten only two levels in JavaScript?

arr.flat(2). The argument is the depth; the default is 1.

How do I flatten a list of lists in Python without a loop?

list(itertools.chain.from_iterable(nested)). It is the fastest pure-Python option and reads clearly.

Does flat() remove empty slots?

Yes. [1, , 3].flat() gives [1, 3]. Empty arrays inside the list disappear too, because they contribute no elements.

What is the time complexity of flattening?

O(n) in the total number of elements for the comprehension, chain, flat and the generator. The sum(nested, []) and repeated concat versions are O(n²).

Where this skill pays off

The string-recursion trap and the quadratic sum() trick are both "looks fine, fails later" bugs — exactly what reviewers of AI-generated code are paid to catch. If that kind of analysis appeals to you, read what makes one coding solution better than another or try the free code comparison lab.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy