Python Morsels Exercise

Flatten deeply nested iterable-of-iterables

3 bonuses 6 hints 17 solutions 744 users solved 54 reviews

In this exercise, we're going to work on flattening iterables. I'd like you to write a function deep_flatten that accepts a list of lists (or lists of tuples and lists) and returns a flattened version of that list of lists.

It should work like this:

>>> deep_flatten([[(1, 2), (3, 4)], [(5, 6), (7, 8)]])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> deep_flatten([[1, [2, 3]], 4, 5])
[1, 2, 3, 4, 5]

In the examples above, we're returning a list. Your deep_flatten function should return an iterable, not necessarily a list.

Your deep_flatten function can assume that no strings will be passed to it. We'll deal with strings later.

Bonus 1

This is just a preview of the problem statement.

This exercise includes 3 bonuses and 6 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨