In this article, well take a look at how we can find a string in a list in Python.
Find a String in a List in Python
There are various approaches to this problem, from the ease of use to efficiency.
Using the in operator
We can use Pythons in operator to find a string in a list in Python. This takes in two operands a and b, and is of the form:
Here, ret_value is a boolean, which evaluates to True if a lies inside b, and False otherwise.
We can directly use this operator in the following way:
Output
We can also convert this into a function, for ease of use.
Output
This is the most commonly used, and recommended way to search for a string in a list. But, for illustration, well show you other methods as well.
Using List Comprehension
Lets take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item.
Consider the list below:
If you want to search for the substring Hello in all elements of the list, we can use list comprehensions in the following format:
This is equivalent to the below code, which simply has two loops and checks for the condition.
In both cases, the output will be:
As you can observe, in the output, all the matches contain the string Hello as a part of the string. Simple, isnt it?
Using the any[] method
In case you want to check for the existence of the input string in any item of the list, We can use the any[] method to check if this holds.
For example, if you wish to test whether AskPython is a part of any of the items of the list, we can do the following:
Output
Using filter and lambdas
We can also use the filter[] method on a lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call.
Output
We do have what we expected! Only one string matched with our filter function, and thats indeed what we get!
Conclusion
In this article, we learned about how we can find a string with an input list with different approaches. Hope this helped you with your problem!
References
- JournalDev article on finding a string in a List
- StackOverflow question on finding a string inside a List