How to check if Python list contains string

Introduction

Given an input list of strings and a search keyword. We want to check if the search keyword is found in the input list (not necessarily an exact match). In other words, if the search keyword is a substring of at least one string in the input list then it is considered a match.

Check substring

In Python, to check if a string is a substring of another, we can do that in multiple ways. For example using the (in) operator…

We can also use the find function against a string as follows…

In this post, we are going to use the first method. Back to our main question…

Check list contains substring

Consider the following input list, we want to search for the keyword ‘cisco’ using different methods…

  • Iterate through the list in a classical way…

  • A more pythonic way is to use a generator expression with the (any) operator. Here is how to do that…

To understand what that means, the expression

is called a generator expression. It is an object, it must be invoked to iterate through all of its items on demand. For example…

When using (any) operator with this generator expression, if any value is True, the final result is True as well like a logical OR.

  • Instead of using a generator expression, we can also use a list comprehension. Take a look…

What does that mean ? Well, the expression

is called a list comprehension, it produces a new list where all items contain the search keyword. If the length is greater than zero, that means at least one string in the input list contains the search keyword so it returns True.

  • Another way to to check if the search keyword exists in the input list is to convert the input list into a long string then use the (in) operator. Take a look…

Finding all matches

So far we were trying to find if there is a match. To print the actual matches, we can do that in a one liner as follows…

References

For more information about generators in Python you may check the following article

Thanks for visiting. Please use the comments section below for questions.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *