Skip to content
Exercise · Comprehensions · lesson 7 of 8

Exercise: flatten a matrix

Write a function flatten(matrix). It returns a new list of all the elements of the nested list matrix: first the elements of the first row, then the second, and so on, in their original order.

  • flatten([[1, 2], [3, 4]]) → [1, 2, 3, 4]
  • flatten([[5], [], [6, 7]]) → [5, 6, 7]
  • flatten([]) → []

Constraints: matrix is a list of lists of numbers; rows may have different lengths and may be empty; an empty matrix gives an empty list; the function does not change matrix itself.

Do not add extra imports unless the task says so explicitly.

flatten.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way