Python Check if suffix matches with any string in given list?


Many times we need to analyze if a given word is present in a given list. That helps us in further processing the business logic for the data. In this article we see how to find if a given suffix which is a string is present in a list with many strings.

Using any

The any() function in python returns True if an item is present in an iterable. If nto it will return False. So in the below program we design if clauses to check for the presence or absence of the given string in the list.

Example

 Live Demo

# Given List
lstA = ["Tue", "Fri", "Sun"]

# String to check
str = 'Sun'
# use any
if any(str in i for i in lstA):
   print(str,"is present in given list.")
else:
   print(str, "is absent from the given list.")

Output

Running the above code gives us the following result −

Sun is present in given list.

Use filter

In the below program we see how to use filter function. This function returns an iterator when the items are filtered through a function to test if the item is accepted or not. Then we convert the result of filter function to a list and check the length of the list. If the length is greater than zero then we say the string is present else it is absent.

Example

 Live Demo

# Given List
lstA = ["Tue", "Fri", "Sun"]

# String to check
str = 'Wed'
# use filter
if len(list(filter(lambda x: str in x, lstA))) != 0:
   print(str,"is present in given list.")
else:
   print(str, "is absent from the given list.")

Output

Running the above code gives us the following result −

Wed is absent from the given list.

Updated on: 12-Jan-2021

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements