2

I am doing a basic computer science course and came across a strange occurrence whilst doing some basic python code. (added print functions for debugging purposes)

#Defines a function that checks if a word is a palindrome or not
def is_palindrome(word):
    word_list = []
    for x in range(0, len(word)):
        word_list.append(word[x])
    word_list_reversed = word_list
    print (word_list)
    word_list_reversed.reverse()
    print (word_list)
    print (word_list_reversed)
    if (word_list == word_list_reversed):
        print("True")
    else:
        print("False")
is_palindrome(str(input("Enter a word: ")))

This function should check if the input word is a palindrome or not. However, when I use the list.reverse() function on the word_list_reversed variable it also reverses the word_list variable.

Enter a word: hello

['h', 'e', 'l', 'l', 'o']

['o', 'l', 'l', 'e', 'h']

['o', 'l', 'l', 'e', 'h']

True

As you can see, the word_list variable is as it should be until the world_list_reversed variable is reversed. I am not looking for alternate solutions to finding palindromes, just an answer as to why this happens.

Community
  • 1
  • 1

2 Answers2

2

In Python, as in many other OO languages, lists are assigned by reference. Thus, when you do:

word_list_reversed = word_list

You are simply making word_list_reversed point to the same memory address as word_list. That's why "both lists" are changed when you reverse one - because they are the same.

To make it work in your example, you can do something like:

from copy import copy
word_list_reversed = copy(word_list)

This will replicate word_list's elements in a brand new list.

lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48
2

When you executed

word_list_reversed = word_list

you made them the same list.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101