Find palindromes of list of strings Python

In this article, we will Find palindromes of list of strings Python. We will check all elements of a list that contains strings and see if it has palindrome strings. We will do this by using multiple techniques using filter() join()

Find palindromes of list of strings Python


Filter() Method:

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

Syntax:

filter(function, sequence)

Parameters:

  • function: a function that tests if each element of a sequence true or not.
  • sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.
  • Returns:returns an iterator that is already filtered

Join() Method:

join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator.
This function joins elements of a sequence and makes it a string.
Syntax: string_name.join(iterable)

Parameters:

  • Iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set
  • Return Value: The join() method returns a string concatenated with the elements of iterable.

1. Find palindromes of list of strings Python using filter() lambda and join()


  • First, we create a list.
  • Then we are writing a lambda function that is taking the string as input.
  • Then this lambda function is reversing this string and comparing with the original string.
  • If both the strings matches, it means this is a palindrome string.
  • Finally, the filter function is appending the list with the palindrome string.
  • Then print the resultant list.
print("Method 1")
orglist=['apple','katak','malayalam','orange']
result=filter(lambda x: (x=="".join(reversed(x))),orglist)
print(list(result))

Output:
Method 1
[‘katak’, ‘malayalam’]

2. Find palindromes of list of strings Python using lambda ,join(),appebd()


  • First we create a list.
  • Then we are writing a lambda function that is taking the string as input.
  • Then this lambda function is reversing this string and comparing with the original string.
  • If both the strings matches , it means this is a palindrome string.
  • Finally we are appending this string to a new list, that will contain all palindrome strings.
  • Then print resultant list.
print("Method 2")
orglist=['apple','katak','malayalam','orange']
str= lambda x: x=="".join(reversed(x))
lst=[]
for i in orglist:
    if str(i)==True:
        lst.append(i)

print(lst)

Output:

Method 2
[‘katak’, ‘malayalam’]