ternary operator

Alex Martelli aleax at aleax.it
Fri Feb 7 18:14:21 EST 2003


Andrew Koenig wrote:

>>> Then how would you write the following loop?
>>> 
>>> i = 0;
>>> while i < len(n) and x[i] != y:
>>> i += 1
   ...
> Alex>     i = x.index(y)
> Alex> is, I think, the best approach in Python.
> 
> But that doesn't really answer the question, does it?

It answered the literal question you posed (with s/n/x/)
though not the one you meant (we bots are like that;-).


> Moreover, I think that loops that use "break" statements
> are harder to reason about than ones that don't.

Everything else being equal, yes.  However, everything
else is rarely equal.  In particular, Python's "for" loop is
most often the simplest and most direct way to iterate
on any iterable; the "while" equivalent is lower-level and
less intuitive, more often than not.  So, whenever you
need to potentially cease iterating before the end of the
sequence, "break" enters the picture.  Consider, for
example, advancing a file to the first line that equals
"xop\n", if any.  With for and break:

    for aline in thefile:
        if aline=="xop\n": break

pretty simple.  With while and without break it's, hmmm...:

    aline = thefile.readline()
    while aline and aline != "xop\n":
        aline = thefile.readline()

I don't agree that this is "harder to reason about" than
the for cycle above.  The repeated calls to readline, and
the more complicated expression on the while clause,
in my opinion make this more complicated.

The situation is not all that different for the case of (e.g.
assuming x is a tuple):

i = 0
while i < len(n) and x[i] != y:
    i += 1

versus:

for i, xi in enumerate(x):
    if xi != y: break

the structures are similar to the "iterate on a file" cases.
A for - cum - break has two salient points:

for <variables> in <iterator>:
    if <condition-satisfied on variables>: break

you only need to identify and understand "iterator" and
"condition-satisfied".  With a while and no break:

<set up initial variables>
while <not finished yet> and not <condition-satisfied>:
    <obtain new values for variables>

these statements may require you to identify and
understand as many as four salient points -- the set up,
the not-finished, the condition-satisfied, and the
obtain-new.  Even though one of the four is often
trivial enough to ignore, even in those cases the 3:2
ratio in "numbers of salient points you need to identify
and understand" still bids fair to make the "for" easier
even with its break -- and the need to join two
logical expressions (one studying whether the iteration
is finished, one studying whether the current point in
the iteration satisfies a condition) into a longer one with
'and' doesn't make things any simpler -- even when 'and'
short-circuits (as we agree it had better;-).


Alex





More information about the Python-list mailing list