1

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'
DavidG
  • 24,279
  • 14
  • 89
  • 82
Kaleab Woldemariam
  • 2,567
  • 4
  • 22
  • 43
  • 1
    `word=[w for w in word_list if w==w[::-1]]` ? – Chris_Rands Oct 06 '17 at 11:55
  • 1
    Possible duplicate of [How to check for palindrome using Python logic](https://stackoverflow.com/questions/17331290/how-to-check-for-palindrome-using-python-logic) – Chris_Rands Oct 06 '17 at 11:58
  • This may not be the best way of testing for palindromes, but I can't reproduce your issue. Running your code I get `word == ['avallava', 'emirime']`. – glibdud Oct 06 '17 at 12:11

3 Answers3

1

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']

Stephen
  • 171
  • 3
  • 3
0

@Chris_Rands answer solved the problem. word=[w for w in word_list if w==w[::-1]]

Kaleab Woldemariam
  • 2,567
  • 4
  • 22
  • 43
0

a=['aba','abc','lil','ozx'] b=[] for i in a: if i==i[::-1]: b.append(i)

print(b)

Saif
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – user11717481 Sep 17 '22 at 20:47