Coding style
Bruno Desthuilliers
onurb at xiludom.gro
Tue Jul 18 05:17:02 EDT 2006
PTY wrote:
> Bob Greschke wrote:
>
>><rurpy at yahoo.com> wrote in message
>>news:1153168968.995422.198360 at m73g2000cwd.googlegroups.com...
>>
>>>PTY wrote:
>>>
>>>>Which is better?
>>>>
>>>>lst = [1,2,3,4,5]
>>>>
>>>>while lst:
>>>> lst.pop()
>>>>
>>>>OR
>>>>
>>>>while len(lst) > 0:
>>>> lst.pop()
>>>
>>>A dozen posts, but nobody has posted the right
>>>answer yet, so I will :-)
>>>
>>>It doesn't matter -- use whichever you prefer (*)
>>>This is an angels on the head of a pin issue.
>>>
>>>(*) -- If your code is part of an existing body of
>>>code that uses one or the other style consistently,
>>>then you should do the same.
>>>
>>
>>I'd go even one step further. Turn it into English (or your favorite
>>non-computer language):
>>
>>1. While list, pop.
>>
>>2. While the length of the list is greater than 0, pop.
>>
>>Which one makes more sense? Guess which one I like. CPU cycles be damned.
>>:)
>>
>>Bob
>
>
>
> It looks like there are two crowds, terse and verbose.
Nope, there are two crowds: those who RTFM, and those who don't.
> I thought terse
> is perl style and verbose is python style.
s/terse/cryptic/
s/verbose/readable/
Python is much more readable than Java because it's *less* verbose than
Java.
> BTW, lst = [] was not what
> I was interested in :-)
Nor is it the correct functional equivalent of your code snippet.
> I was asking whether it was better style to
> use len() or not.
The idiomatic solution is clearly derivable from Python's language
documentation : in a boolean context, empty lists (etc...) eval to
False. FWIW, it's also more generic (you could have an object supporting
pop() but not __len__()), less error-prone, and can allow optimisations
(a container may know that it is empty without computing it's length).
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list