I am checking a list of strings if every string in the list is palindrome or not. I need a for loop to test the function for all strings in the list.
l=["Anna", "Civic", "Computer" ]
First, i write a code just like this below:
def is_it_palindrome(list):
for x in list:
if x.upper() == x[::-1].upper():
return True
else:
return False
when I run this code, it only returns one True. not True True False Then I change my code:
def is_it_palindrome(list):
for x in list:
if x.upper() == x[::-1].upper():
print("True")
else:
print("False")
It works. However, Could anyone tell me why the first one do not work and the second one is true or not. Thank you.
The reason that your first def isn't work is since you are using return
with causing your function to return value and stop the loop.
I suggest you to use map
built-in function as following, just notice that it can be written in a better way
str_list =["Anna", "Civic", "Computer" ]
def is_it_palindrome(word):
return word.upper() == word[::-1].upper()
list(map(is_it_palindrome, str_list))
EDIT - this can also be written with lmbda function, which is more Pythonic way, but I got confuse with it some times.
str_list =["Anna", "Civic", "Computer" ]
list(map(lambda x: x.upper() == x[::-1].upper() , str_list ))