[Tutor] creating pop method for stack class
Christopher Spears
cspears2002 at yahoo.com
Fri Jul 18 07:32:54 CEST 2008
>
> 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
>
> ?
>
I see what you mean. I have tested it, and I have gotten a weird result:
>>> def shorten(lst):
... lst = lst[:-1]
...
>>> lista = [1,2,3,4]
>>> shorten(lista)
>>> print lista
[1, 2, 3, 4]
>>> lista = [1,2,3,4]
>>> lista = lista[:-1]
>>> print lista
[1, 2, 3]
>>>
Strange...why does it work outside of the function but not in it? Let me try something else:
>>> def shorten(lst):
... lst = lst[:-1]
... return lst
...
>>> lista = [1,2,3,4]
>>> shorten(lista)
[1, 2, 3]
>>> print lista
[1, 2, 3, 4]
>>> lista = shorten(lista)
>>> print lista
[1, 2, 3]
>>>
Huh, how do you explain that?
More information about the Tutor
mailing list