Ifs and assignments

Chris Angelico rosuav at gmail.com
Thu Jan 2 22:49:41 EST 2014


On Fri, Jan 3, 2014 at 2:33 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> However, I don't think we should treat this as specific to if statements:
>
>     for i, obj in enumerate(alist + blist + clist as items):
>         items[i] = process(obj)
>
>
> Is that really better than this?
>
>     items = alist + blist + clist
>     for i, obj in enumerate(items):
>         items[i] = process(obj)

It definitely shouldn't be specific to if statements, though I think
that's probably going to be the biggest use-case (chained if/elif
blocks). Maybe a for loop isn't the best other example, but I
frequently work with places where I want to call some function and
keep iterating with the result of that until it returns false:

while (var = func())
{
    ....
}

In Python, that gets a lot clunkier. The most popular way is to turn
it into an infinite loop:

while True:
    var = func()
    if not var: break
    ....

which is pretty much how the C version will compile down, most likely.
It feels like an assembly language solution. The point of a while loop
is to put its condition into the loop header - burying it inside the
indented block (at the same indentation level as most of the code)
conceals that, and this is a very simple and common condition. So this
is what I'd cite as a second use-case:

while func() as var:
    ....

And that definitely looks more readable.

ChrisA



More information about the Python-list mailing list