Flatten a Nested List
Beginner · Write the code · from Python itertools: Powerful Tools for Working with Iterables
From the lesson: Python itertools: Powerful Tools for Working with Iterables
Imagine you have a Swiss Army knife for loops. Instead of writing complicated nested loops and temporary lists, you pull out the right tiny tool and the job is done in one clean line.
Read the lessonUse chain.from_iterable to flatten the nested list [[1, 2], [3, 4], [5, 6]] into a single flat list. Print the result.
from itertools import chain
nested = [[1, 2], [3, 4], [5, 6]]
# Flatten and print
More itertools exercises
- Generate All Coin Flip OutcomesIntermediate
- Find All 2-Letter PermutationsIntermediate
- Predict the takewhile OutputIntermediate
- Compute a Running TotalBeginner
- Group Numbers as Even or OddAdvanced
- Fix the groupby BugAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz