Search List for String In Python

Python list is used to store multiple items in a single variable of an object. We can store multiple strings in a list easily. The list of strings can be searched in different ways to find string. We can search string in a list partially or regex or the start of the string etc. In this tutorial, we examine different methods like in operator , list operator etc. to find a string in a list.

Search List for String Using in Operator

Python provides the in operator in order to check the existence of specified values or objects in the specified list or object. We can use the “in” operator in order to search and check if a string exists in a list. The “in” operator returns a boolean value like True or False. If the specified string exists in the given list the return value is True and if does not exist the return value is False.

names = ["ismail","ali","ahmet","elif"]

if "ahmet" in names:
   print("ahmet exists in the list names")

Search List for String Using List Comprehension

Another method to find a string in a list is using list comprehension. List comprehension simply iterates over all elements of the list and we can check the string in every step for the current item. In the following example, we search the string “ahmet” in the list named “names”.

names = ["ismail","ali","ahmet","elif"]

matches = [m for m in names if "ahmet" in m]

Search List for String Using any() Method

Python provides the any() method which is provided as a built-in. The any() method is used to check if the specified values or objects exist in the specified list, array, tuple, etc. which is an iterable object.

names = ["ismail","ali","ahmet","elif"]

if any("ahmet" in word for word in names):
   print("ahmet exists in the list names")
   print("ahmet does not exist in the list names")

Search List for String Using Filter and Lambdas

Python provides the lambda operation in order to run code block like a function without defining a function and filter() method is used to filter a given iterable object according to the specified function. We can use both the filter() method and lambda function in order to search a string inside a list. If the specified string is found in the list it is returned as result like below.

names = ["ismail","ali","ahmet","elif"]

result = filter(lambda w: 'ahmet' in w, names)


Leave a Comment