ternary operator

Alex Martelli aleax at aleax.it
Fri Feb 7 18:05:46 CET 2003


<posted & mailed>

Andrew Koenig wrote:

> David> I think that's POOR programming practice!
> 
> Then how would you write the following loop?
> 
>         i = 0;
>         while i < len(n) and x[i] != y:
>                 i += 1

Hmmm, the fact that i<len(n) gives no guarantee that
i is a valid index on x, in general.  So, I'm not sure
if you may not perchance mean i<len(x) instead, which
might be a more ordinary case.

If so, and x is a list, then:
    i = x.index(y)
is, I think, the best approach in Python.

If x was (for example) a tuple, and/or assuming that n
is not necessarily x but may refer to another sequence
which is known to be no longer than x, then I might
code this as:

for i in range(len(n)):
    if x[i] == y: break

or, in Python 2.3 -- if n is actually x, then:

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

or without the n <-> x identification, then:

for i, thingy in enumerate(x):
    if i>=len(n) or thingy == y: break


None of this is meant to deny the usefulness of
the short-circuiting and/or operators.  It's just
that there are several attractive alternatives for
this _specific_ case in Python, but of course many
other cases exist where relying on and/or short-
circuit semantics yields the most elegant solution.


Alex





More information about the Python-list mailing list