Use the list as a logical condition, which evaluates to False only if the list is empty:
>>> while a: ... print a.pop() ... 4 3 2 1
Not only is this shorter, it is also more efficient (1.49 ms versus 1.9 ms for a list of 10,000), since it should only check if there is a first element:
$ python -mtimeit -c 'a=range(10000) while len(a): a.pop()' 10000 loops, best of 3: 1.9 msec per loop $ python -mtimeit -c 'a=range(10000) while a: a.pop()' 1000 loops, best of 3: 1.49 msec per loop
You can also use reversed() to get a reverse iterator:
>>> for n in reversed(a): ... print n ... 4 3 2 1
Or in one line:
print '\n'.join(map(str, reversed(a)))
Please note that this will not remove items from the list. If necessary, you can achieve this with del a[:] .
marcog
source share