Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a list without modifying the original list in Python

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!

like image 946
Hana Avatar asked Jan 21 '17 08:01

Hana


2 Answers

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 ints in the list).

like image 180
hiro protagonist Avatar answered Sep 29 '22 08:09

hiro protagonist


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
like image 43
Yousaf Avatar answered Sep 29 '22 08:09

Yousaf