Categories
Python Answers

How to flatten a shallow list in Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to flatten a shallow list in Python?”

list2= [[‘image00’, ‘image01’], [‘image10’], []]
new=[]
for i in list2:
for j in i:
new.append(j)
print(new)

Leave a Reply

Your email address will not be published. Required fields are marked *