I'am searching on the internet quite long but I'am not succesfull. I have a list of words:
words = ["kayak", "pas", "pes", "reviver", "caj", "osel", "racecar","bizon", "zubr", "madam"]
And I need to print only words that are palindromes. I found this solution:
words = ["kayak", "pas", "pes", "reviver", "caj", "osel", "racecar","bizon", "zubr", "madam"]
palindrome = list(filter(lambda x: (x == "".join(reversed(x))), words))
print(palindrome)
But I dont like it. I have to use FOR loop somehow and I dont know how. I tried many things but still dont get it.
Thank you.
CodePudding user response:
Here is the example with explanations:
words = ['kayak', 'pas', 'pes', 'reviver', 'caj', 'osel', 'racecar','bizon', 'zubr', 'madam']
# Start with empty list
palindromes = []
# Iterate over each word
for word in words:
# Check if word is equal to same word in reverse order
is_palindrome = (word == word[::-1])
# Append to results if needed
if is_palindrome:
palindromes.append(word)
print(palindromes)
# => ['kayak', 'reviver', 'racecar', 'madam']
CodePudding user response:
With a for loop:
palindrome = []
for i in words:
if i == "".join(reversed(i)):
palindrome.append(i)
print(palindrome)
Or list comprehension:
palindrome = [i for i in words if i == "".join(reversed(i))]
print(palindrome)
Output:
['kayak', 'reviver', 'racecar', 'madam']