Reputation: 3003
I am trying to test if a list of strings are palindromes using list comprehension or slicing. I converted str1
to list using word_list=str1.split()
. However, the palindrome test,
word=[w for w in word_list if w[0:9:1]==w[0:9:1][::-1]]
works for only the first word. Since the words have different lengths, I am wondering if there are concise way of writing the code without using common loops?
str1='avallava si padre emirime'
Upvotes: 1
Views: 2271
Reputation: 1
a=['aba','abc','lil','ozx'] b=[] for i in a: if i==i[::-1]: b.append(i)
print(b)
Upvotes: 0
Reputation: 401
The line below iterates through word_list, keeps the words which are palindromes and stores them as a list.
palindromes = [w for w in word_list if w == w[::-1]]
If world_list = ['avallava', 'si', 'padre', 'emirime']
,
then palindromes = ['avallava', 'emirime']
Upvotes: 1
Reputation: 3003
@Chris_Rands answer solved the problem.
word=[w for w in word_list if w==w[::-1]]
Upvotes: 0