Apr-18-2018, 03:56 PM
You could write a generator that makes it look nicer.
>>> def top(count, items): ... items = iter(items) ... while count > 0: ... yield next(items) ... count -= 1 ... >>> buf = ['hello', 'bye', 'now', 'before', 'after'] >>> for element in top(3, buf): ... print(element) ... hello bye nowOn the other hand, something like that is already available in
itertools
:>>> import itertools >>> for element in itertools.islice(buf, 3): ... print(element) ... hello bye now