Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a stack (reverse list), is there an isempty() method?

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.

like image 964
Jason S Avatar asked Dec 28 '10 15:12

Jason S


2 Answers

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()
like image 50
Ray Avatar answered Oct 13 '22 18:10

Ray


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[:].

like image 8
moinudin Avatar answered Oct 13 '22 16:10

moinudin