-1

I'm writing a function to check whether the integer is palindrome on Leetcode. Most of cases are acceptable. But there is a special case which is 10, why the output of my code return True. The idea for my code is convert integer to str and then convert it to list. Then reverse the list and compare two lists whether are the same.

Is my idea or code does not work out right or there are sth I missed, would be appreciate if someone can point out. Here is the code screenshot


initial_list=list(str(x))

temp = initial_list

initial_list.reverse()

if temp == initial_list:
    print('True')
else:
    print('False')
Grismar
  • 27,561
  • 4
  • 31
  • 54
QZhong
  • 1
  • 2
  • Please put a copy of the relevant code in your question https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question – Grismar Nov 29 '21 at 08:02
  • Add the code as text ( not image ). – balderman Nov 29 '21 at 08:04
  • You'll find that every test case will be `True`, because you're comparing the list to itself. By assigning `initial_list` to `temp`, both variables now point to the same list, you need to reverse a copy instead. – Grismar Nov 29 '21 at 08:06
  • @Grismar, thank for your comment, I realize that after viewing your and Paul's comment. It works now. – QZhong Nov 29 '21 at 08:09
  • 1
    If Paul's answer is satisfying, please click the checkmark to accept it, so the question no longer appears unanswered. – Grismar Nov 29 '21 at 08:11

1 Answers1

3

To create a copy of your initial list, use: temp = initial_list.copy()

Otherwise, temp is just a reference to the original initial_list.

Try printing temp again after applying initial_list.reverse()

Paul
  • 1,801
  • 1
  • 12
  • 18
  • https://levelup.gitconnected.com/understanding-reference-and-copy-in-python-c681341a0cd8 could help you understand the difference better. – Paul Nov 29 '21 at 08:08