Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there builtin iterators in Python?

We have builtin iterables like lists, tuples, and dictionaries to name a few. We can also create our own iterable objects by implementing an __iter__ method in the class. We can also do that iterator objects by implementing an __iter__ and a __next__ method, but are there builtin iterators like there are builtin iterables?

like image 544
multigoodverse Avatar asked Nov 16 '25 19:11

multigoodverse


1 Answers

The following builtins return iterators in Python 3: enumerate(), filter(), iter() (of course), map(), reversed() and zip().

In Python there are also a lot of native python methods that return iterators, for example checkout the itertools module (the hint is in the name!).

However, to pedantically answer your question, no there are not builtins that are iterators (I can't think of a good use case for this), but as tobias_k says list() and others are not iterables either and merely return then.


Testing that iterator classes (not objects) exist in builtins (thanks to FHTMitchell):

import builtins
import collections.abc

def isiteratorclass(obj):
    if not isinstance(obj, type):
        return False
    return issubclass(obj, collections.abc.Iterator)


[key for key, value in vars(builtins).items() if isiteratorclass(value)]
# --> ['enumerate', 'filter', 'map', 'reversed', 'zip']
like image 151
Chris_Rands Avatar answered Nov 19 '25 09:11

Chris_Rands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!