user9983860
user9983860

Reputation:

Why my initial variable changes even it is a copy?

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.

Upvotes: 0

Views: 59

Answers (1)

grooveplex
grooveplex

Reputation: 2539

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.

Upvotes: 3

Related Questions