Stack iteration (reverse list), is there isempty () method?

What is 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 could not find the isempty method, and checking the length every time seems wrong somehow.

+6
python stack iteration
source share
3 answers

The usual convention for containers is that they are True, not empty, and False is empty, so you can simply do:

 while a: print a.pop() 
+22
source share

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

+6
source share

Python: What is the best way to check if a pool is empty?

Stack (python)

+2
source share

All Articles