Pesky reverse()

Paul Rubin http
Thu Jan 8 21:30:50 EST 2004


engsolnom at ipns.com writes:
> print my_list.reverse()  doesn't work.

The reverse() method reverses the list in place and returns None.

> But  I want both a 'forward' and 'reverse' list:
> 
> new_list = my_list  # should save a 'forward' copy, right? Nope

No, both new_list and my_list are bound to the same list, like in C
you might have two pointers to the same structure.  To make a copy, use

   new_list = my_list[:]

> my_list.reverse() actually reverses both copies, since Python is a bit too
> helpful sometimes, and I understand why.
> 
> So the question is, how do I get a forward and reverse list?

   new_list = my_list[:]
   new_list.reverse()



More information about the Python-list mailing list