Pesky reverse()

E

engsolnom

I need to use the built-in method 'reverse', but notice strange behavior.
Foe example:

print my_list.reverse() doesn't work.

new_list = my_list.reverse() doesn't work.

my_list.reverse()
print my_list does work. (displays reversed list)

But I want both a 'forward' and 'reverse' list:

new_list = my+list # should save a 'forward' copy, right? Nope
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?

Thanks......Norm.
 
P

Paul Rubin

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()
 
S

Sean Ross

I need to use the built-in method 'reverse', but notice strange behavior.
[snip]

new_list = my+list # should save a 'forward' copy, right? Nope
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?
forward = range(10)
reverse = forward[:] # copy
reverse.reverse()
print forward [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print reverse [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

HTH
Sean
 
E

Elaine Jackson

list1=[1,2,3]
list2=list1[:] ## "cloning"
list1.reverse()==None 1
list1 [3, 2, 1]
list2
[1, 2, 3]


|
| I need to use the built-in method 'reverse', but notice strange behavior.
| Foe example:
|
| print my_list.reverse() doesn't work.
|
| new_list = my_list.reverse() doesn't work.
|
| my_list.reverse()
| print my_list does work. (displays reversed list)
|
| But I want both a 'forward' and 'reverse' list:
|
| new_list = my+list # should save a 'forward' copy, right? Nope
| 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?
|
| Thanks......Norm.
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,044
Latest member
RonaldNen

Latest Threads

Top