Search code examples
pythonfunctionipythonpalindromewords

Python - Palindrome function: Receiving error "list indices must be integers or slices, not str"


I've been trying to use the following code to create a palindrome. I have a txt file named 'lowercasewords' which is essentially a list full of words in lowercase where I am querying from and I want to append words that are spelled the same reversed into a list named 'lines2'.

The code is below:

def palindrome():
    lines = open('lowercasewords.txt','r').read().splitlines()
    lines2 = []
    for x in lines:
        if (lines[x]) == (lines[x][::-1]) is True:
            lines2.append(str(x))
        else:
            pass
    print(lines2)

However, I receive the error:

TypeError: list indices must be integers or slices, not str

Can anyone help??? I can show that the word 'level' is the same reversed:

str(lines[106102]) == str(lines[106102][::-1])
True

Solution

  • When you run for x in lines: then x is set to the current word in the list. Your code is then trying to get the index of that word in lines. This is the equivalent of saying lines["hello"], which doesn't make any sense. The loop is already setting x to the value you want so you do not need to refer to lines any more.

    You also do not need to check if something is True, the if statement is already testing for a statement being True or false.

    You can fix it by simply replacing

    if (lines[x]) == (lines[x][::-1]) is True:
    

    with

    if x == x[::-1]: