Sometimes, we want to take the first N items from a generator or list with Python.
In this article, we’ll look at how to take the first N items from a generator or list with Python.
How to take the first N items from a generator or list with Python?
To take the first N items from a generator or list with Python, we can use the slice syntax for lists and itertools.islice
method for generators.
For instance, we write
top_5 = array[:5]
to return the first 5 items from the array
list.
And we get the first items from a generator with
import itertools
top_5 = itertools.islice(my_list, 5)
We call islice
with the my_list
generator and 5 to return an iterator with the first 5 items.
Conclusion
To take the first N items from a generator or list with Python, we can use the slice syntax for lists and itertools.islice
method for generators.