[Tutor] iterators

eryksun eryksun at gmail.com
Sun Jan 19 02:40:29 CET 2014


On Sat, Jan 18, 2014 at 6:24 PM, Keith Winston <keithwins at gmail.com> wrote:
>
> I guess it makes sense that iter() returns a type iterator.

`iter(obj)` returns `obj.__iter__()` if the method exists and the
result is an iterator, i.e. has a `__next__` method.

Otherwise if `obj.__getitem__` exists, it returns a generic sequence
`iterator`. This steps through the sequence `obj[0]`, `obj[1]`, and so
on, until it encounters either `IndexError` or `StopIteration`.

`iter(callable, sentinel)` returns a `callable_iterator`. This returns
`callable()` until either the result equals `sentinel` or it
encounters `StopIteration`. For example:

    >>> sentinel = 2
    >>> it = iter(iter(range(5)).__next__, sentinel)
    >>> type(it)
    <class 'callable_iterator'>
    >>> list(it)
    [0, 1]

`reversed(obj)` returns `obj.__reversed__()`, if it exists. It doesn't
check the type of the result:

    class C:
        __reversed__ = lambda s: 3.14

    >>> reversed(C())
    3.14

Otherwise if `obj` is a sequence (`__getitem__`, `__len__`, and not a
`dict`), it returns a `reversed` instance. This iterates from
`obj[len(obj) - 1]` down to `obj[0]`.


More information about the Tutor mailing list