[Tutor] creating pop method for stack class

John Fouhy john at fouhy.net
Fri Jul 18 06:26:14 CEST 2008


On 18/07/2008, Christopher Spears <cspears2002 at yahoo.com> wrote:
>  How come the stack doesn't shrink when I pop off the last value?  I tested the code in the interpreter:
>
>  >>> lista = [1,2,3,4]
>  >>> lista[:len(lista)-1]
>  [1, 2, 3]
>  >>> lista = lista[:len(lista)-1]
>  >>> lista
>  [1, 2, 3]

First, a tip:

Instead of lista[:len(lista)-1], you can (and should) just write lista[:-1].

Now, what if we wrap that in a function:

>>> def shorten(lst):
...   lst = lst[:-1]  # identical to: lst = lst[:len(lst)-1]
...

Then test it:

>>> lista = [1, 2, 3, 4]
>>> shorten(lista)

What do you think will be the result of:

>>> print lista

?

PS.  You wrote:

>     def stackpop(self):
>         length = len(self)
>         if length == 0:
>             print "Empty list!"

If you're trying to pop from an empty stack, this is an error
condition.  Rather than printing a message, the correct way to handle
errors in python is by raising exceptions.  e.g.

def stackpop(self):
    if len(self) == 0:
        raise IndexError    # or you could define your own exception...

>     def peek(self):
>         length = len(self)
>         if length == 0:
>             return 0

The same applies here -- peeking at an empty stack should be an error
too.  Otherwise, how can you tell the difference between an empty
stack and a stack where the top item happens to be a 0?

-- 
John.


More information about the Tutor mailing list