Home > database >  Palindrome strings comparison in a list using a function [duplicate]
Palindrome strings comparison in a list using a function [duplicate]

Time:10-07

Hi i have got a list of items in strings in a list. I want see if these words in strings are palindromes using a function. So far i have got this code,

input_list = ['taco cat', 'bob', 'davey']
def palindromes(x):
    for x in input_list:
        if x == x[::-1]
            return True
        else:
            return False 
output = [palindromes(x)]
print(output)

the result should be in a list [ True, True, False ] what am i doing wrong here plz?

CodePudding user response:

You should probably simplify the palindromes function to just handle a single string:

def palindrome(x):
    x = x.replace(" ", "")  # given your sample data
    return x == x[::-1]

And then use a comprehension:

output = [palindrome(x) for x in input_list]

Or, using map:

output = [*map(palindrome, input_list)]

CodePudding user response:

Try:

input_list = ['taco cat', 'bob', 'davey']
def palindromes(x):
   x_no_spaces = x.replace(' ', '')
   return x_no_spaces == x_no_spaces[::-1]

print([palindromes(i) for i in input_list]

CodePudding user response:

Try this:

input_list = ['taco cat', 'bob', 'davey']


def palindromes(x):
    return [i == i[::-1] for i in x]


output = palindromes(input_list)
print(output)

[False, True, False]
  • Related