[Tutor] range efficiency

eryksun eryksun at gmail.com
Sat May 11 08:59:57 CEST 2013


On Fri, May 10, 2013 at 5:19 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?

At the start of a for loop, the interpreter gets an iterator for the
iterable. The latter is  evaluated from the expression or
expression-list (tuple). If this fails it raises a TypeError.

iteration is an object protocol, using the special methods __iter__
and __next__, and the exception StopIteration. An iterator maintains
its own state. You can get an iterator manually with built-in iter()
and step through it with built-in next().

    >>> it = iter('abc')
    >>> type(it)
    <class 'str_iterator'>
    >>> next(it), next(it), next(it)
    ('a', 'b', 'c')
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

    >>> it = iter(range(5))
    >>> type(it)
    <class 'range_iterator'>
    >>> list(it)
    [0, 1, 2, 3, 4]
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration


More information about the Tutor mailing list