17. Flatten a list
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
rows = [[1, 2], [3], [4, 5, 6]][1, 2, 3, 4, 5, 6]Example 2
rows = [["a"], [], ["b"]]["a", "b"]Example 3
rows = [[1], [[2, 3]]][1, [2, 3]]Constraints
rowshas 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).
- You need two loops: one over the lists in
rows, and inside it one over the items of each list. - Append each item to a new list. An item that is itself a list still counts as one item: append it, don't open it.
- The same two loops fit in one list comprehension, written in the same order:
[item for row in rows for item in row].
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.