I'm trying to use the reverse() method in the following way:
>>> L=[1,2,3]
>>> R=L
>>> L.reverse()
>>> L
[3, 2, 1]
>>> R
[3, 2, 1]
Why does it reverse R as well? How do I keep the original list and create a reversed on?
Thanks!
you need to make a copy of your list
L=[1,2,3]
# R=L
R = L[:]
L.reverse()
or more directly (reversing using slice notation):
R = L[::-1]
if you just write R = L
then R
is just a new reference on the same list L
.
if you also need to copy the elements in your list, use copy.deepcopy
; R = L[:]
only produces a shallow copy (which is fine in your case where there are only int
s in the list).
To avoid reversing R
, you need a copy of L
To make a copy, change
R=L <---- this is not copying L in to R
to
R= L[:] <---- this will create a copy of L in to R
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With