73. Interleave lists
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,Noneand empty strings. - An empty list of lists, or lists that are all empty, give
[].
Example 1
Input
lists = [[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
Input
lists = [[1, 2], [], [3, 4, 5]]Output
[1, 3, 2, 4, 5]ExplanationThe empty list is skipped every round.
Example 3
Input
lists = []Output
[]ExplanationNo lists, no items.
Constraints
listshas 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).
iter(items)gives an iterator over a list, andnext(it)hands out its next item each time it is called. When the items run out,next()raisesStopIteration.- Keep a list of iterators. Each round, call
next()on each one in turn; catchStopIterationto drop an iterator that has run out. Stop when none are left. zip()stops at the shortest list.itertools.zip_longest()pads withNone, and removing the padding afterwards would also remove realNoneitems.
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.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.