---
title: "Discussion on \"7 Different Ways to Flatten a List of Lists in Python\" | Hashnode"
description: "Discussion on \"7 Different Ways to Flatten a List of Lists in Python\". Learn how to \"unlist\" (unnest) a irregular list; nested lists of tuples, ints or strings; with or without recursion; or using itertools python"
url: "https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7"
---

[Feed](https://hashnode.com/feed) /

Discussion

# [7 Different Ways to Flatten a List of Lists in Python](https://miguendes.me/python-flatten-list?utm_source=hashnode&utm_medium=feed)

Learn how to "unlist" (unnest) a irregular list; nested lists of tuples, ints or strings; with or without recursion; or using itertools python

Dec 12, 2020 · 12 min read · miguendes.me  
Updated Jul 23, 2022  
Read the article

-   [#python](https://hashnode.com/tag/python)
-   [#python3](https://hashnode.com/tag/python3)
-   [#tutorial](https://hashnode.com/tag/tutorial)

## Written by

[Miguel Brito](https://hashnode.com/@miguendes)

@miguendes · London, UK

  
[View profile](https://hashnode.com/@miguendes)

Machine Learning Software Engineer - Hobbyst Technical Writer - Interested in Software Testing, Best Practices, Scalability, and Python.

AI Software Engineer based in London, UK with 6+ years of professional experience developing and releasing software in different programming languages - Hobbyist Technical Writer - Interested in Software Testing, Best Practices, Scalability, Machine Learning/AI, and Python.

## Responses 4

Markdown supported · ⌘↵ to post

[Gyansetu](https://hashnode.com/@gyansetu)

[Oct 13, 2023](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/65299637069d0e037f9a7bf1)

Gyansetu's Python section is a Python enthusiast's sanctuary! Their in-depth tutorials and insights provide invaluable guidance for Python learners and professionals alike. Thank you for nurturing our Python prowess! For more info:- [gyansetu.in/blogs/future-scope-of-python-in-india](https://www.gyansetu.in/blogs/future-scope-of-python-in-india/)

[Hynek Černoch](https://hashnode.com/@hynekcer)

[Dec 18, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdc3422b78ac62dff80aa9a)

All functions measured by a line `%timeit some_function(l)` are measured incorrectly. A time in about hundreds of nanoseconds to get a list of 9 \* 1000 numbers is a nonsense. You will see that the result doesn't depend on a number of items.

It is because any code after a `yield` command is postponed until you enumerate the output values. If you put a slow sleep command after a `yield` line then you will see no difference because it run never. Even a generator expression command `%timeit (x for x in range(1000000000))` is similarly fast as the same for `range(1)`.

A correct measurement is by `%timeit list(some_function(l))` or `%timeit for _ in some_function(l): pass`

The fastest code for flattening is `flatten_chain(l)` because the expression `itertools.chain(*lst)` uses only a library function call and no Python loops.

[Miguel Brito](https://hashnode.com/@miguendes)

[Dec 18, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdc3422b78ac62dff80aa9a#reply-5fdc6aff1485f22e24b33250)

You're absolutely correct. I missed that. So much so that for the tests I always convert it to list.

I'll edit the article with the correct timings.

Thanks for pointing out!

Edit: Fixed it!

[Ruud van der Ham](https://hashnode.com/@ruudvanderham)

[Dec 17, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdbceceb78ac62dff80a5c9)

Here's a different, non recursive, solution for deep flattening:

```
def flatten(bad):
    good  = []
    while bad:
        e = bad.pop()
        if isinstance(e, list):
            bad.extend(e)
        else:
            good.append(e)
    return good[::-1]
```

Very likely quite fast as well.

[Hynek Černoch](https://hashnode.com/@hynekcer)

[Dec 18, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdbceceb78ac62dff80a5c9#reply-5fdc35ddb78ac62dff80aac7)

This require a `copy.deepcopy()` to prevent a side effects because the original input parameter is completely broken by this function.

[Ruud van der Ham](https://hashnode.com/@ruudvanderham)

[Dec 18, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdbceceb78ac62dff80a5c9#reply-5fdc4a7bb78ac62dff80ac65)

[Hynek Černoch](https://hashnode.com/@hynekcer) Good point. It is true that the original list will be destroyed. But if that doen't matter a deep copy is not required.

[Ruud van der Ham](https://hashnode.com/@ruudvanderham)

[Dec 18, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fdbceceb78ac62dff80a5c9#reply-5fdcdfc91485f22e24b33d31)

[Hynek Černoch](https://hashnode.com/@hynekcer) Maybe it would be better to use this quite different function as an inline flatten, very much like list.sort() or list.remove(). The return value is then always None and the list will be replaced by the flattened version. That can be implemented like:

```
def flatten_inplace(lst):
    build  = []
    while lst:
        e = lst.pop()
        if isinstance(e, list):
            lst.extend(e)
        else:
            build.append(e)
    lst.extend(build[::-1])
```

[HEE JAE CHOI](https://hashnode.com/@gmlwo530)

[Dec 13, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fd633f5f60e3973bae6c4d0)

Great article!!

By the way, is it typo?

```
def flatten_recursive(lst: List[Any]) -> Iterable[Any]:
    """Flatten a list using recursion."""
    for item in lst:
        if isinstance(item, list):
            yield from flatten(item)  # This line! I think it will be `yield from flatten_recursive(item)`
        else:
            yield item
```

[Miguel Brito](https://hashnode.com/@miguendes)

[Dec 13, 2020](https://hashnode.com/posts/python-flatten-list/5fd49556b6e5766805757aa7/comment/5fd633f5f60e3973bae6c4d0#reply-5fd6651627af257395892223)

Thanks [HEE JAE CHOI](https://hashnode.com/@gmlwo530), and yes, this is a typo!

Thanks for flagging it, I've just fixed it. I renamed it before publishing to make it easier to understand and forgot to double check it in IPython.

This is the correct version:

```
def flatten_recursive(lst: List[Any]) -> Iterable[Any]:
    """Flatten a list using recursion."""
    for item in lst:
        if isinstance(item, list):
            yield from flatten_recursive(item)
        else:
            yield item
```
