What's the best way to iterate over a stack in Python?
a = [1,2,3,4]
while (len(a) > 0)
print a.pop()
# prints 4, 3, 2, 1 in sequence
I couldn't find an isempty
method, and checking the length each time seems wrong somehow.
The usual convention for containers is that they are True while not empty and False when empty, so you can just do:
while a:
print a.pop()
Use the list as a boolean condition which evaluates to False
only if the list is empty:
>>> while a:
... print a.pop()
...
4
3
2
1
Not only is this more concise, it is also more efficient (1.49ms vs 1.9ms for a list of 10,000) since it only has to 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)))
Note that this will not remove the elements from the list. If necessary, you can achieve that with del a[:]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With