[Tutor] range efficiency

eryksun eryksun at gmail.com
Sun May 12 12:21:41 CEST 2013


On Sat, May 11, 2013 at 10:41 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
> On Fri, May 10, 2013 at 3: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?
>
> The gritty details say "yes":
>
>     http://docs.python.org/2/reference/compound_stmts.html#the-for-statement
>
> when it says: "The expression list is evaluated once; it should yield
> an iterable object."

On the other hand,  at each iteration the target_list is assigned
"using the standard rules for assignments". The following expressions
are valid targets for assignment: Name (identifier), Attribute,
Subscript (slices), and a list/tuple of the latter. 3.x also accepts
starred targets in a list/tuple, as spec'd in PEP 3132.

For an attribute target of value.identifier, "value" can use an
expression. For a subscript target of value[slice], both "value" and
"slice" can use expressions (the ASDL treats an index as a kind of
slice). Here's an example with a subscript target:

    >>> even, odd = [0]*3, [0]*3
    >>> for i, (odd if i % 2 else even)[i // 2] in enumerate(range(6)):
    ...     print(i, even, odd)
    ...
    0 [0, 0, 0] [0, 0, 0]
    1 [0, 0, 0] [1, 0, 0]
    2 [0, 2, 0] [1, 0, 0]
    3 [0, 2, 0] [1, 3, 0]
    4 [0, 2, 4] [1, 3, 0]
    5 [0, 2, 4] [1, 3, 5]

Not that I'm recommending anyone do something this silly. Maybe
someone else can come up with a more practical example. But I prefer
the target_list to be as simple as possible, preferably just names in
the local scope.

Reference (3.3.1):
http://hg.python.org/cpython/file/d9893d13c628/Parser/Python.asdl


More information about the Tutor mailing list