Comparison problem
Peter Hansen
peter at engcorp.com
Mon Nov 28 08:04:57 EST 2005
Tim Henderson wrote:
> peter
(Thanks for clarifying to whom you were responding... I saw the other
post but wouldn't have responded since it didn't seem to be in response
to one of mine. :-) )
> would not the more correct way to do this be short circuit
> evaluation. somthing along lines of
>
> if (len(item) > 0) and (item[0] == '-'): pass
This is "correct" only in a narrow sense. I wouldn't call it "correct
Python" if I saw it in code around here. Most likely (since this always
depends on context), I would replace it with this:
if item and item[0] == '-':
pass
I think it's probably unlikely that the first test would be needed only
on that one line, so it's even more likely that "if item" test would be
done first, by itself, and then other tests on item[0] would be done.
If this was code that needed high performance (i.e. had been detected
with proper profiling as a serious bottleneck) then the slicing approach
would be better (as Fredrik demonstrated).
Hmm... just realized we're going way off track, since we actually have
the original code here and don't need to comment on hypotheticals.
It appears to me that the original input is being treated as some sort
of fixed-length record, with certain characters and text in predefined
positions, specified by index number. With that in mind, I'd actually
say the original code is just fine with "if item[0:1] == '-'" and given
the context it is pretty readable (ignoring the awful formatting with no
whitespace around operators) and "correct". Using ".startswith()" might
have been equally appropriate, but without knowing more detail of the
input data I couldn't say.
-Peter
More information about the Python-list
mailing list