[Tutor] Re: Tutor digest, Vol 1 #1594 - 15 msgs
Jeff Shannon
jeff@ccvcorp.com
Wed, 24 Apr 2002 18:05:00 -0700
> Message: 12
> From: "Wesley Abbott" <wesleyabbott@hotmail.com>
> To: tutor@python.org
> Date: Wed, 24 Apr 2002 16:02:41 -0600
> Subject: [Tutor] Problems understanding List reverse()
>
> Hello everyody.
>
> I am having a slight problem with relation to 'list.reverse'. I am able ot
> get the reverse to work if a list is static, but if I have a user input
> information it does not seem to abe able to reverse.
It has nothing to do with the user input, it's because you're not using
list.reverse() quite right. :)
As someone else mentioned, that reversel() function is dangerous. Here's why:
>>> def reversel(alist):
... alist.reverse()
... return alist
...
>>> mylist = [1, 2, 3, 4]
>>> print mylist
[1, 2, 3, 4]
>>> otherlist = reversel(mylist)
>>> print otherlist
[4, 3, 2, 1] # seems to work fine so far, but...
>>> print mylist
[4, 3, 2, 1] # the original list is reversed, too!
>>>
That's probably not what was intended or expected. As was pointed out, this can be
fixed by making a *copy* of the list before you reverse it:
>>> def reversel(alist):
... listcopy = alist[:]
... listcopy.reverse()
... return listcopy
>>>
Now, as for your "user input" problem...
>>> print mylist
[4, 3, 2, 1]
>>> print mylist.reverse()
None # It doesn't work!
>>> print mylist
[1, 2, 3, 4] # Or does it?
>>>
You tried to print the result of list.reverse(), but since it reverses the list
*in-place*, there is *no* result. It reversed the list all right, and then returned
None. In fact, this was done deliberately so that the mistake you made with your
reversel() function would be less likely -- if list.reverse() returned the reversed
list, it would be easy to forget that it also *modified* the original list.
Hope that helps...
Jeff Shannon
Technician/Programmer
Credit International