A list of lists named xss can be flattened using a nested list comprehension:

flat_list = [
    x
    for xs in xss
    for x in xs
]

The above is equivalent to:

flat_list = []

for xs in xss:
    for x in xs:
        flat_list.append(x)

Here is the corresponding function:

def flatten(xss):
    return [x for xs in xss for x in xs]

This is the fastest method. As evidence, using the timeit module in the standard library, we see:

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' '[x for xs in xss for x in xs]'
10000 loops, best of 3: 143 usec per loop

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'sum(xss, [])'
1000 loops, best of 3: 969 usec per loop

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'reduce(lambda xs, ys: xs + ys, xss)'
1000 loops, best of 3: 1.1 msec per loop

Explanation: the methods based on + (including the implied use in sum) are, of necessity, O(L**2) when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of M items each: the first M items are copied back and forth L-1 times, the second M items L-2 times, and so on; total number of copies is M times the sum of x for x from 1 to L excluded, i.e., M * (L**2)/2.

The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.

Answer from Alex Martelli on Stack Overflow
Top answer
1 of 16
7504

A list of lists named xss can be flattened using a nested list comprehension:

flat_list = [
    x
    for xs in xss
    for x in xs
]

The above is equivalent to:

flat_list = []

for xs in xss:
    for x in xs:
        flat_list.append(x)

Here is the corresponding function:

def flatten(xss):
    return [x for xs in xss for x in xs]

This is the fastest method. As evidence, using the timeit module in the standard library, we see:

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' '[x for xs in xss for x in xs]'
10000 loops, best of 3: 143 usec per loop

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'sum(xss, [])'
1000 loops, best of 3: 969 usec per loop

$ python -mtimeit -s'xss=[[1,2,3],[4,5,6],[7],[8,9]]*99' 'reduce(lambda xs, ys: xs + ys, xss)'
1000 loops, best of 3: 1.1 msec per loop

Explanation: the methods based on + (including the implied use in sum) are, of necessity, O(L**2) when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have L sublists of M items each: the first M items are copied back and forth L-1 times, the second M items L-2 times, and so on; total number of copies is M times the sum of x for x from 1 to L excluded, i.e., M * (L**2)/2.

The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.

2 of 16
2463

You can use itertools.chain():

>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))

Or you can use itertools.chain.from_iterable() which doesn't require unpacking the list with the * operator:

>>> import itertools
>>> list2d = [[1,2,3], [4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))

This approach is arguably more readable than [item for sublist in l for item in sublist] and appears to be faster too:

$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
20000 loops, best of 5: 10.8 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 5: 21.7 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 5: 258 usec per loop
$ python3 -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;from functools import reduce' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 5: 292 usec per loop
$ python3 --version
Python 3.7.5rc1
๐ŸŒ
Real Python
realpython.com โ€บ python-flatten-list
How to Flatten a List of Lists in Python โ€“ Real Python
December 22, 2024 - A common approach to flatten a list of lists is to use a for loop to iterate through each sublist. Then you can add each item to a new list with the .extend() method or the augmented concatenation operator (+=).
Discussions

Flatten an array in Python - Code Review Stack Exchange
I would like to get some code review for my recursive implementation of python flatten array method. Write a piece of functioning code that will flatten an array of arbitrarily nested array... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
September 8, 2018
algorithm - What is the fastest way to flatten arbitrarily nested lists in Python? - Stack Overflow
Load table without geometry from PostgreSQL into QGIS via Python ... Have armed forces ever transfused their wounded soldiers with blood forcibly collected from enemy fighters or occupied civilian populations? Properly transfinitely Euclidean rings of integers ยท What is this movie or TV show where a man discovers a baby with incredible strength? ... If a planet had no tilt and a ring at the same tilt of the planet, what would the temperature be at the equator ยท xint: calc array ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Flattening and unflattening a nested list of numpy arrays - Stack Overflow
There are many recipes for flattening a nested list. I'll copy a solution here just for reference: def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinst... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Flatten multi dimensional array in python 3 - Stack Overflow
Since you're using Python 3, you can take advantage of yield from with a recursive function. It has been introduced in Python 3.3. As a bonus, you can flatten arbitrary nested lists, tuples, sets or ranges: More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to efficiently flatten a nested list of arbitrary depth in python?
r/learnpython on Reddit: How to efficiently flatten a nested list of arbitrary depth in Python?
June 30, 2025 -

This is a list of numbers: Input: L = [1, [2], [3, 4, [5]]] Output: [1, 2, 3, 4, 5]

What would be the most optimal and Pythonic way to do this?

Top answer
1 of 12
28
The most Pythonic way is probably going to be using recursion to build up a new list - while recursion should ideally be avoided where possible, when you get into arbitrarily deep data structures it's usually the clearest way. This approach is simple, clear, and doesn't use any of the more uncommon features that the reader might not be immediately familiar with: def flatten_list(lst): flat_list = [] for element in lst: if isinstance(element, list): flat_list.extend(flatten_list(element)) else: flat_list.append(element) return flat_list L = [1, [2], [3, 4, [5]]] print(flatten_list(L)) This approach isn't likely to be the most performant, though, as solutions using things like list.extend aren't incredibly efficient because of all the temporary intermediate lists that have to be created in memory during the execution. If you have tested this method and found it's too slow, you can try using generators. This is more pythonic and more efficient, but yield and yield from are not encountered anywhere near as often as many other Python features and a lot of developers are unaware that they exist at all, so they could be a source of confusion. Note that the result of the function has to be passed to the list() function if it's printed out directly as it's a generator, although it can be iterated through as normal without calling list(). def flatten_list(nested_list): for item in nested_list: if isinstance(item, list): yield from flatten_list(item) else: yield item L = [1, [2], [3, 4, [5]]] print(list(flatten_list(L))) for x in flatten_list(L): print(x)
2 of 12
11
Recursive
๐ŸŒ
Leocon
leocon.dev โ€บ blog โ€บ 2021 โ€บ 09 โ€บ how-to-flatten-a-python-list-array-and-which-one-should-you-use
How to flatten a python list/array and which one should you use | Leonidas Constantinou
September 5, 2021 - This is the most Pythonic way. Even though nested list comprehension is not easy on the eye, it's a really simple method. For those who understand list comprehensions, you can skip the explanation. list_1D = [item for sub_list in list_2D for item in sub_list]Copied to clipboard! If we were to code this using nested loops we will write it like this:
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ examples โ€บ flatten-nested-list
Python Program to Flatten a Nested List
sum() combines my_list and [ ] to produce a flattened list. from functools import reduce my_list = [[1], [2, 3], [4, 5, 6, 7]] print(reduce(lambda x, y: x+y, my_list)) ... In the above example, reduce() applies the lambda function to all the elements of my_list.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-convert-a-nested-list-into-a-flat-list
Python | Convert a nested list into a flat list - GeeksforGeeks
July 11, 2025 - Pythonโ€™s Itertool is a module that provides various functions that work on iterators to produce complex iterators. ... import itertools # Original list lis = [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] flatList = list(itertools.chain(*lis)) print("Original List:", lis) print("Flattened List:", flatList)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ list-flatten-in-python-flattening-nested-lists
List Flatten in Python โ€“ Flattening Nested Lists
March 20, 2023 - A nested for loop is a for loop inside another for loop. This is how you can flatten out a list of lists for loop: list_of_lists = [[12, 45, 2], [3, 7, 3, 1], [23, 89, 10, 9]] flattened_list_of_lists = [] for sublist in list_of_lists: for num in sublist: flattened_list_of_lists.append(num) print(flattened_list_of_lists) # [12, 45, 2, 3, 7, 3, 1, 23, 89, 10, 9] The code above loops through each dimension of the array and appends them into an empty list I called flattened_list_of_lists with the append() method.
Find elsewhere
Top answer
1 of 3
9

Your code looks fine, however to improve it, you should use a proper test system like pytest or unittest. To demonstrate, here is your code when using pytest, and making the test proper (you don't need to test every specific item:

def flatten(input_array):
    result_array = []
    for element in input_array:
        if isinstance(element, int):
            result_array.append(element)
        elif isinstance(element, list):
            result_array += flatten(element)
    return result_array


def test01():
    results = flatten([1, [2, 3, [4]], 5, [[6]]])
    assert results == [1, 2, 3, 4, 5, 6]


def test02():
    results = flatten([1, [2, 3, [4], []], [], 5, [[], [6]]])
    assert results == [1, 2, 3, 4, 5, 6]

And here are the results:

C:\PycharmProjects\codereview\tests>pytest scratch_14.py 
======================== test session starts ========================
platform win32 -- Python 3.7.0, pytest-3.6.2, py-1.5.4, pluggy-0.6.0
rootdir: C:\PycharmProjects\codereview\tests, inifile:
plugins: cov-2.5.1, celery-4.2.0
collected 2 items

scratch_14.py ..                                               [100%]

===================== 2 passed in 0.09 seconds ======================

This is much easier to set up, and less code to write to validate if the solution is correct. You asked: Is usage of TypeError exception justified?
I don't actually see any code referencing a type error. Did you forget to put it in? Or are you referring to the use of isinstance? If so, that code is fine.
Hope this helps!

2 of 3
7

Your function only deals with ints and lists. While it may be fine in the context of the question, this doesn't feel Pythonic at all as it disregard any other kind of iterable and any other type of data:

>>> flatten([1, (2, 3), [4.5], 6])
[1, 6]

Instead, you could make use of the iterator protocol to have a generic flatten function:

def flatten(iterable):
    try:
        iterator = iter(iterable)
    except TypeError:
        yield iterable
    else:
        for element in iterator:
            yield from flatten(element)

Usage being:

>>> list(flatten([1, (2, 3), [4.5], 6]))
[1, 2, 3, 4.5, 6]

However, there are two potential issues with this approach:

  • you may not like that flatten is now a generator: change it to an helper function and wrap it with a call to list:

    def _flatten_generator(iterable):
        # previous code
    
    def flatten(iterable):
        return list(_flatten_generator(iterable))
    
  • you won't be able to handle strings at all as individual characters are still a string and you will run into a:

    RecursionError: maximum recursion depth exceeded while calling a Python object
    

    So you may want to add an explicit check for str at the beginning of the function.

Top answer
1 of 3
95

Here's a recursive approach that is string friendly:

nests = [1, 2, [3, 4, [5],['hi']], [6, [[[7, 'hello']]]]]

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

print list(flatten(nests))

returns:

[1, 2, 3, 4, 5, 'hi', 6, 7, 'hello']

Note, this doesn't make any guarantees for speed or overhead use, but illustrates a recursive solution that hopefully will be helpful.

2 of 3
32

It doesn't have to be recursive. In fact, an iterative solution is often faster because of the overhead involved in function calls. Here's an iterative version I wrote a while back:

def flatten(items, seqtypes=(list, tuple)):
    for i, x in enumerate(items):
        while i < len(items) and isinstance(items[i], seqtypes):
            items[i:i+1] = items[i]
    return items

Haven't tested the performance of this specific implementation, but it is probably not so great because of all the slice assignments, which could end up moving a lot of memory around. Still, don't assume it has to be recursive, or that it's simpler to write it that way.

This implementation does have the advantage of flattening the list "in place" rather than returning a copy, as recursive solutions invariably do. This could be useful when memory is tight. If you want a flattened copy, just pass in a shallow copy of the list you want to flatten:

flatten(mylist)                # flattens existing list
newlist = flatten(mylist[:])   # makes a flattened copy

Also, this algorithm is not limited by the Python recursion limit because it's not recursive. I'm certain this will virtually never come into play, however.

2021 edit: it occurs to me that the check for the end of the list might be better handled with try/except because it will happen only once, and getting the test out of the main loop could provide a performance beneft. That would look like:

def flatten(items, seqtypes=(list, tuple)):
    try:
        for i, x in enumerate(items):
            while isinstance(items[i], seqtypes):    
                items[i:i+1] = items[i]
    except IndexError:
        pass
    return items

With some further tweaking to use the x returned by enumerate instead of accessing items[i] so much, you get this, which is either mildly or significantly faster than the original version up top, depending on the size and structure of your lists.

def flatten(items, seqtypes=(list, tuple)):
    try:
        for i, x in enumerate(items):
            while isinstance(x, seqtypes):    
                items[i:i+1] = x
                x = items[i]
    except IndexError:
        pass
    return items
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Flatten a List of Lists in Python | note.nkmk.me
August 20, 2023 - In Python, you can flatten a list of lists (nested list, 2D list) using itertools.chain.from_iterable(), sum(), or list comprehensions. ... Use ravel() or flatten() to flatten a NumPy array (numpy.ndarray).
๐ŸŒ
Kanaries
docs.kanaries.net โ€บ topics โ€บ Python โ€บ python-flatten-list
Python Flatten List: 8 Methods to Flatten Nested Lists โ€“ Kanaries
February 10, 2026 - When to use: Only when your data is already in NumPy arrays or when you are doing numerical computation. Do not import NumPy just to flatten a list of Python objects -- it adds overhead and dependency for no benefit. The more-itertools library provides collapse(), which deep-flattens any iterable ...
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ articles โ€บ how-to-flatten-list-in-python
How to flatten list of lists in Python?
Instead of a lambda function, we can also use the concat() function defined in the operator module as an argument to cumulatively append the sublists to flatten. ... from functools import reduce from operator import concat nestedlist = [ [1, ...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ python-how-to-flatten-list-of-lists
Python: How to Flatten a List of Lists
September 20, 2023 - We are also using the flat attribute to get a 1D iterator over the array in order to achieve our goal. However, this approach is relatively slow: import numpy regular_list = [[1, 2, 3, 4], [5, 6, 7], [8, 9]] flat_list = list(numpy.concatenate(regular_list).flat) print('Original list', regular_list) print('Transformed list', flat_list) ... The task of flattening can also be performed by using built-in functions that Python offers.
๐ŸŒ
OneUptime
oneuptime.com โ€บ home โ€บ blog โ€บ how to flatten a list of lists in python
How to Flatten a List of Lists in Python
January 25, 2026 - If you are working with numeric data and have NumPy installed, its flatten or ravel methods are very fast. import numpy as np # Works when all sublists have the same length nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] arr = np.array(nested) flat = arr.flatten().tolist() print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9] # For uneven sublists, use hstack nested_uneven = [[1, 2], [3, 4, 5], [6]] flat = np.hstack(nested_uneven).tolist() print(flat) # [1, 2, 3, 4, 5, 6]
๐ŸŒ
Vultr
docs.vultr.com โ€บ python โ€บ examples โ€บ flatten-a-nested-list
Python Program to Flatten a Nested List | Vultr Docs
December 11, 2024 - This code demonstrates a deep nesting level where the list contains other lists at different depths. It systematically flattens these structures into a simple, one-dimensional list. Pythonโ€™s itertools module provides a method called chain, which can be helpful, especially in combination with itertools.chain.from_iterable to flatten lists that are only one level deep.
Top answer
1 of 3
5

I was looking for a solution to flatten and unflatten nested lists of numpy arrays, but only found this unanswered question, so I came up with this:

def _flatten(values):
    if isinstance(values, np.ndarray):
        yield values.flatten()
    else:
        for value in values:
            yield from _flatten(value)

def flatten(values):
    # flatten nested lists of np.ndarray to np.ndarray
    return np.concatenate(list(_flatten(values)))

def _unflatten(flat_values, prototype, offset):
    if isinstance(prototype, np.ndarray):
        shape = prototype.shape
        new_offset = offset + np.product(shape)
        value = flat_values[offset:new_offset].reshape(shape)
        return value, new_offset
    else:
        result = []
        for value in prototype:
            value, offset = _unflatten(flat_values, value, offset)
            result.append(value)
        return result, offset

def unflatten(flat_values, prototype):
    # unflatten np.ndarray to nested lists with structure of prototype
    result, offset = _unflatten(flat_values, prototype, 0)
    assert(offset == len(flat_values))
    return result

Example:

a = [
    np.random.rand(1),
    [
        np.random.rand(2, 1),
        np.random.rand(1, 2, 1),
    ],
    [[]],
]

b = flatten(a)

# 'c' will have values of 'b' and structure of 'a'
c = unflatten(b, a)

Output:

a:
[array([ 0.26453544]), [array([[ 0.88273824],
       [ 0.63458643]]), array([[[ 0.84252894],
        [ 0.91414218]]])], [[]]]
b:
[ 0.26453544  0.88273824  0.63458643  0.84252894  0.91414218]
c:
[array([ 0.26453544]), [array([[ 0.88273824],
       [ 0.63458643]]), array([[[ 0.84252894],
        [ 0.91414218]]])], [[]]]

License: WTFPL

2 of 3
0

Here is what I come up with, which turned out to be ~30x faster than iterating over the nested list and loading individually.

def flatten(nl):
    l1 = [len(s) for s in itertools.chain.from_iterable(nl)]
    l2 = [len(s) for s in nl]

    nl = list(itertools.chain.from_iterable(
        itertools.chain.from_iterable(nl)))

    return nl,l1,l2

def reconstruct(nl,l1,l2):
    return np.split(np.split(nl,np.cumsum(l1)),np.cumsum(l2))[:-1]

L_flat,l1,l2 = flatten(L)
L_reconstructed = reconstruct(L_flat,l1,l2)

A better solution solution would work iteratively for an arbitrary number of nested levels.

๐ŸŒ
Adamdimech
code.adamdimech.au โ€บ flattening-nested-lists-or-arrays-in-python
Flattening nested lists or arrays in Python | Adam Dimech's Coding Blog
There may be a requirement to flatten a list of lists in Python in order to extract useful information more easily. Hereโ€™s a procedure for flatting nested lists using NumPy. Letโ€™s say that we have a list of lists in Python that consists of 6 rows of three rows of 3 tuples: my_list = np.arange(54).reshape(6, 3, 3) array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]], [[27, 28, 29], [30, 31, 32], [33, 34, 35]], [[36, 37, 38], [39, 40, 41], [42, 43, 44]], [[45, 46, 47], [48, 49, 50], [51, 52, 53]]])
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-recursively-flatten-a-nested-list-in-python-398238
How to recursively flatten a nested list in Python | LabEx
The basic idea behind the recursive flattening algorithm is to iterate through the elements of the nested list and check if each element is a list. If the element is a list, the algorithm recursively flattens that list and appends the flattened ...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ how to flatten list in python?
How to flatten List in Python? - Scaler Topics
February 6, 2024 - Syntax: The syntax used for the flatten() method to flatten lists in Python is as below: ... numpy_array: The NumPy array that you want to flatten. It should be created from the nested list that needs to be flattened.