Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63023

Re: Ifs and assignments

References <52C59FF6.5000607@allsup.co> <mailman.4816.1388709915.18130.python-list@python.org> <52c62fa8$0$30001$c3e8da3$5496439d@news.astraweb.com>
Date 2014-01-03 14:49 +1100
Subject Re: Ifs and assignments
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.4823.1388720985.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Jan 3, 2014 at 2:33 PM, Steven D'Aprano
<steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Ifs and assignments Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-01-02 19:45 -0500
  Re: Ifs and assignments Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-03 14:33 +1100
    Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 14:49 +1100
      Re: Ifs and assignments Roy Smith <roy@panix.com> - 2014-01-02 23:14 -0500
        Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 15:25 +1100
        Re: Ifs and assignments Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-03 04:29 +0000
      Re: Ifs and assignments Duncan Booth <duncan.booth@invalid.invalid> - 2014-01-03 15:46 +0000
    Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 14:55 +1100
      Re: Ifs and assignments Roy Smith <roy@panix.com> - 2014-01-02 23:00 -0500
        Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 15:08 +1100

csiph-web