Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm writing a program to identify palindromes using Python, using lists. However, my program always states that the input word is a palindrome, even if it clearly isn't

word = input("Type a word, and I'll tell you if it's a palidrome or not: ")

word = " ".join(word)

new_word = word.split() #forms a list from user-inputted word

print(new_word)

variable = new_word

variable.reverse() #reverses word list 

print(variable)

if variable == new_word:

    print("This is a palidrome")

else:

    print("This is not a palidrome")

1 Answer

0 votes
by (25.1k points)

This is because on line 5, when you use variable = new_word, instead of copying the value of new_word into variable it merely creates a pointer. So, now both variable and new_word are pointing to the same value in memory. Later on, when you reverse new_word and then compare variable and new_word it will always return true as they are both pointing to the same variable.

To avoid this you can use the deepcopy method in copy module like this:

import copy

variable = copy.deepcopy(new_word)

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...