#254 · Iterators and generators · Beginner · 40 XP · about 7 min
Write a generator take_n(iterable, n) that yields the first n items of iterable, in order. If the iterable has fewer than n items, it yields all of them.
The iterable can be a list, a string, another generator, or something that never ends, like itertools.count(). So take_n must not turn it into a list: it takes the items one at a time, only when they are asked for, and never takes more than `n` items from it. Whatever comes after them is left in place for the next reader.
list(take_n('python', 3)) # returns ['p', 'y', 't'] list(take_n([1, 2], 5)) # returns [1, 2] from itertools import count list(take_n(count(100), 4)) # returns [100, 101, 102, 103] it = iter([1, 2, 3, 4, 5]) list(take_n(it, 2)) # returns [1, 2] list(it) # returns [3, 4, 5]
n is 0 or more. When n is 0, nothing is yielded.
First solves only, ranked by stars and then time.