Arithmetic with Boolean values
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Aug 12 10:06:10 EDT 2012
On Sun, 12 Aug 2012 07:40:30 -0400, Roy Smith wrote:
> In article <502791ea$0$29978$c3e8da3$5496439d at news.astraweb.com>,
> Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>
>> for x in (0,) if len(L)%2 else (0, 1):
>> ...
>>
>> which is even more explicit and simpler to read even though it is
>> longer.
>
> Ugh.
>
> do_stuff()
> if len(L) % 2 == 0:
> do_stuff() # reprocess even-length list
>
> Sure, it's 3 lines instead of one, but dead-obvious what the intention
> is.
Well, sure, for that specific case that would work too. Using a for-loop
to do something once is a little icky. But only a little.
Also, it scales to situations like "repeat 37 times when even, or 82
times when odd" (or any other values).
> There's two problems with all the looping suggestions people have given.
> One is that the computation of whether you need to do it once or twice
> is messy. But, but bigger issue is you're trying to warp what's
> fundamentally a boolean value into a looping construct. That's a
> cognitive mismatch.
Really? You've never used a while loop?
while not finished:
do_something()
There's nothing wrong with having a for-loop which iterates over a
computed set of values:
if len(L)%2:
items = range(len(L)//2 + 1)
else:
items = range(len(L)//2)
for x in items:
...
which can be simplified to:
for x in range(len(L)//2 + len(L)%2):
...
--
Steven
More information about the Python-list
mailing list