ternary operator
Andrew Koenig
ark at research.att.com
Fri Feb 7 12:36:59 EST 2003
>>
>> Then how would you write the following loop?
>>
>> i = 0;
>> while i < len(n) and x[i] != y:
>> i += 1
Alex> Hmmm, the fact that i<len(n) gives no guarantee that
Alex> i is a valid index on x, in general. So, I'm not sure
Alex> if you may not perchance mean i<len(x) instead, which
Alex> might be a more ordinary case.
Right.
Alex> If so, and x is a list, then:
Alex> i = x.index(y)
Alex> is, I think, the best approach in Python.
But that doesn't really answer the question, does it?
Alex> None of this is meant to deny the usefulness of
Alex> the short-circuiting and/or operators. It's just
Alex> that there are several attractive alternatives for
Alex> this _specific_ case in Python, but of course many
Alex> other cases exist where relying on and/or short-
Alex> circuit semantics yields the most elegant solution.
Right.
Moreover, I think that loops that use "break" statements
are harder to reason about than ones that don't.
--
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
More information about the Python-list
mailing list