Which is better?
>
lst = [1,2,3,4,5]
>
while lst:
lst.pop()
>
OR
>
while len(lst) 0:
lst.pop()
>
The former, without a doubt. It says exactly the same thing, since lst
can only be considered false when it is empty. Experienced Python
programmers would scratch their heads at your second formulation.
I doubt there's much in it from a time point of view (though I know as I
write this it will spur someone to use timeit.py to point out I am wrong).
The original while loop changes the actual list, reassigning it
to a new list prevents other items that reference that list from
accessing the changes. As shown above, I recommend
del lst[:]
which should be as fast as python will let one do it. (maybe?
again with those timeit guys... ;)
In article <mailman.8257.1 153158306.27775 .python-list@python.org >,
Steve Holden <steve@holdenwe b.comwrote:
tac-tics wrote:
....
>I'd say the second one. Empty lists are not false. They are empty.
>Long live dedicated boolean data types.
Take them off to where they belong!
Tac-tics is right, an empty list is not False.
Anyway, just for some variety, I think (2) is preferrable
to (1), as is the following
while 1:
try:
lst.pop()
except IndexError:
break
Rather than blindly apply familiar patterns to our work,
I think everyone would agree that coding style in matters
like this should follow the underlying point of the code.
In this case, the body of the test refers implicitly to
the length of the list, since .pop() -(list[a], list[:a])
where a is (len(list) - 1) It's therefore quite appropriate
for the test to be length.
But that's not what he said. He said it was "not false." That's wrong.
It's false. It's just not False.
--
Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
The meaning of life is that it stops.
-- Franz Kafka
>
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.
:)
Comment