50 XP

17. Flatten a list

Intermediate lists comprehensions

Write a function flatten(rows) that takes a list of lists and returns one new list holding all their items: first the items of the first list, then those of the second, and so on, each in its own order.

Only remove one level of lists. When an item of an inner list is itself a list, it stays a list in the result. Inner lists can be empty, and so can rows: then the result is an empty list [].

Example 1

Inputrows = [[1, 2], [3], [4, 5, 6]]
Output[1, 2, 3, 4, 5, 6]
ExplanationEach list's items, one list after another.

Example 2

Inputrows = [["a"], [], ["b"]]
Output["a", "b"]
ExplanationThe empty list adds nothing.

Example 3

Inputrows = [[1], [[2, 3]]]
Output[1, [2, 3]]
Explanation[2, 3] was an item, so it stays a list.

Constraints

  • rows has 0 to 50 lists, each with 0 to 50 items.
  • An item can be any value, including a list.

Submit also runs 4 more tests you can't see.

Practises List Comprehensions (lesson 15).

Code
def flatten(rows):
    """Join a list of lists into one list.

    rows: list of lists; any of them may be empty
    Returns: list, all their items, in order
    """
    # Write your code here
    pass