50 XP

73. Interleave lists

Intermediate lists loops

Write a function interleave(lists) that takes a list of lists and returns one list made by taking their items in turn, like dealing cards: the first item of each list, then the second item of each, and so on.

  • Go through the lists in the order given, each time round.
  • When a list runs out, skip it and carry on with the others until every item has been taken.
  • Every item is kept exactly as it is, including 0, False, None and empty strings.
  • An empty list of lists, or lists that are all empty, give [].

Example 1

Inputlists = [[1, 2, 3], ["a", "b"], [True]]
Output[1, "a", True, 2, "b", 3]
ExplanationRound 1: 1, "a", True. Round 2: 2, "b". Round 3: only 3 is left.

Example 2

Inputlists = [[1, 2], [], [3, 4, 5]]
Output[1, 3, 2, 4, 5]
ExplanationThe empty list is skipped every round.

Example 3

Inputlists = []
Output[]
ExplanationNo lists, no items.

Constraints

  • lists has 0 to 10 lists, each with 0 to 20 items of any kind.

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

Practises Iterators and Generators (lesson 29).

Code
def interleave(lists):
    """Take items from the lists in turn.

    lists: list of lists, of any lengths
    Returns: list, every item, taken one list at a time,
        round after round
    """
    # Write your code here
    pass