[Tutor] Problems understanding List reverse()

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 25 Apr 2002 00:11:28 +0200


On  0, Wesley Abbott <wesleyabbott@hotmail.com> wrote:
> 
> 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. Please help. Code is 
> below. TIA for all your help. I am totally new to programming, coming from a 
> network engineer background. I am going through Wesley Chun's book right 
> now. I also have the O'Reilly Learning to program Python. Once again thanks 
> to all who can help me. I have all the different lists jsut to help me 
> figure this out. Not trying to confuse anybody, :)
> 
> # a simple reverse function
> def reversel(list):
>     list.reverse()
>     return list

First, note this is dangerous - the list you give as an argument is actually
changed! When you do 'a = reversel(alist2)' below, it looks like only a is
the new list, but in fact alist2 itself also changed (and they refer to the
same list - so if you make any changes in either, the other is also changed).

It's better to do something like
a = alist2[:] # make a copy
a.reverse()

> alist = []
> alist2 = [1, 2, 3, 4, 5]
> alist.append(raw_input('Enter a string:  '))
> print alist
> print reversel(alist)
> a = reversel(alist2)
> print a

alist has 1 element, namely the string the user gave as input.

Reversing an 1-element list has no effect :).

If you want to reverse a string, you have to change it into a list, reverse
that, then join the characters together again, something like:

word = raw_input('Enter a string: ')
wordlist = list(word)
wordlist.reverse()
drow = ''.join(wordlist)
print drow

I hope this helps.

-- 
Remco Gerlich