In this article, we’ll take a look at how we can find string in list in Python
Find a String in a List in Python
There are three ways to find a string in a list in Python. They’re as follows:
- With the
inoperator in Python
list comprehensionto find strings in a Python list
- Using the
any() methodto find strings in a list
- Finding strings in a list using the
filter and lambda methodsin Python
Let’s get right into the individual methods and explore them in detail so you can easily implement this in your code.
1. Using the ‘in’ operator to find strings in a list
In Python, the
in operator allows you to determine if a string is present a list or not. The operator takes two operands,
b, and the expression
a in b returns a boolean value.
If the value of
a is found within
b, the expression evaluates to
True, otherwise it evaluates to
ret_value = a in b
ret_value is a boolean, which evaluates to
a lies inside
Here’s an example to demonstrate the usage of the
a = [1, 2, 3] b = 4 if b in a: print('4 is present!') else: print('4 is not present')
4 is not present
To make the process of searching for strings in a list more convenient, we can convert the above into a function. The following example illustrates this:
def check_if_exists(x, ls): if x in ls: print(str(x) + ' is inside the list') else: print(str(x) + ' is not present in the list') ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython'] check_if_exists(2, ls) check_if_exists('Hello', ls) check_if_exists('Hi', ls)
2 is inside the list Hello is inside the list Hi is not present in the list
in operator is a simple and efficient way to determine if a string element is present in a list. It’s the most commonly used method for searching for elements in a list and is recommended for most use cases.
2. Using List Comprehension to find strings
Let’s 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.
List comprehensions can be a useful tool to find substrings in a list of strings. In the following example, we’ll consider a list of strings and search for the substring “Hello” in all elements of the list.
Consider the list below:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']
We can use a list comprehension to find all elements in the list that contain the substring “Hello“. The syntax is as follows:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [match for match in ls if "Hello" in match] print(matches)
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches =  for match in ls: if "Hello" in match: matches.append(match) print(matches)
In both cases, the output will be:
['Hello from AskPython', 'Hello', 'Hello boy!']
As you can observe, in the output, all the matches contain the string
Hello as a part of the string. Simple, isn’t it?
3. Using the ‘any()’ method
The any() method in Python can be used to check if a certain condition holds for any item in a list. This method returns
True if the condition holds for at least one item in the list, and
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:
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] if any("AskPython" in word for word in ls): print('\'AskPython\' is there inside the list!') else: print('\'AskPython\' is not there inside the list')
In the above example, the condition being checked is the existence of the string
"AskPython" in any of the items in the list
ls. The code uses a list comprehension to iterate over each item in the list and check if the condition holds.
If the condition holds for at least one item,
True and the first
if statement is executed. If the condition does not hold for any item,
False and the
else statement is executed.
'AskPython' is there inside the list!
4. 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.
ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] # The second parameter is the input iterable # The filter() applies the lambda to the iterable # and only returns all matches where the lambda evaluates # to true filter_object = filter(lambda a: 'AskPython' in a, ls) # Convert the filter object to list print(list(filter_object))
['Hello from AskPython']
We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!
We have seen that there are various ways to search for a string in a list. These methods include the in operator, list comprehensions, the any() method, and filters and lambda functions. We also saw the implementation of each method and the results that we get after executing the code. To sum up, the method you use to find strings in a list depends on your requirement and the result you expect from your code. It could be a simple existence check or a detailed list of all the matches. Regardless of the method, the concept remains the same to search for a string in a list.
- JournalDev article on finding a string in a List
- StackOverflow question on finding a string inside a List