This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 5: List comprehension

List comprehension exercise

face Josiah Wang Joe Stacey

Here is one more exercise before we move on.

Using list comprehension, write a program to flatten a nested list into a single list. You can assume that there are no further nested lists inside the inner list.

For example, the program would take numbers below and produce [1, 2, 2, 3, 4, 4, 5] as new_numbers.

numbers = [[1, 2], [2, 3, 4], [4, 5]]
new_numbers = ????
assert new_numbers == [1, 2, 2, 3, 4, 4, 5]

No peeking at the solutions until you have tried it! 👀

A possible solution:

numbers = [[1, 2], [2, 3, 4], [4, 5]]
new_numbers = [value for inner_list in numbers for value in inner_list]