0

I'm trying to find Palindrome so I copied the list to another variable but when I use reverse function, both variables gets reversed. why is this happening?

I can use a loop and append from reverse order one by one, but I really want to know why reverse function works this way.

arr = list(input())
ar = arr
ar.reverse()
print(arr, ar)
print("YES" if arr == ar else "NO"

I expect to find palindrome.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 3
    `ar = arr` does not create a copy. Python variables are just name bindings, references, to objects. So when doing `ar = arr` you are simply telling Python: "Now `ar` should point to the same list as `arr`". So by doing `ar.reverse()`, you reverse the list in memory which is the same one that `arr` points to – Tomerikoo Aug 05 '19 at 21:11
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – juanpa.arrivillaga Aug 05 '19 at 21:12
  • You never copied a list. As an aside, please always use the generic [python] tag for *all python related questions* – juanpa.arrivillaga Aug 05 '19 at 21:13

1 Answers1

3

It's because arr.reverse() reverses the list in place (see also help(list.reverse)).

That is, you need to make a copy of the list and then reverse that:

arr = list(input())
ar = arr.copy()
ar.reverse()
print(arr, ar)
print("YES" if arr == ar else "NO")

(Notice how I changed ar = arr to ar = arr.copy())


You could have "diagnosed" this problem yourself using the id function, which returns an unique identifier for each object:

>>> arr = list("foo bar beep boop")
>>> id(arr)
4343238976
>>> ar = arr
>>> id(ar)
4343238976
>>> copied = arr.copy()
>>> id(copied)
4341383968

Notice how id(ar) and id(arr) return the same number (4343238976 in this case), meaning they point to the same object. Meanwhile id(copied) returns a different number, meaning it's a different object.

grooveplex
  • 2,492
  • 4
  • 28
  • 30