How to flatten a shallow list in Python?

Sometimes, we want to flatten a shallow list in Python.

In this article, we’ll look at how to flatten a shallow list in Python.

How to flatten a shallow list in Python?

To flatten a shallow list in Python, we can use the itertools.chain method.

For instance, we write:

import itertools

list_of_menuitems = [['image00', 'image01'], ['image10'], []]

chain = itertools.chain(*list_of_menuitems)
print(list(chain))

We defined the list_of_menuitems list which has lists inside it.

Then we call itertools.chain with the list_of_menuitems used as arguments since we spread it with *.

And then we convert the returned chain iterator to a list with list.

Therefore, we see:

['image00', 'image01', 'image10']

printed.

Conclusion

To flatten a shallow list in Python, we can use the itertools.chain method.