- Find a string in a List in Python
- 1. Using the ‘in’ operator to find strings in a list
- 2. Using List Comprehension to find strings
- 3. Using the ‘any()’ method
- 4. Using filter and lambdas
- Conclusion
- References
- Python Find String in List
- Python Find String in List using count()
- Finding all indexes of a string in the list
- Python Check if List Contains a String
- Use the for Loop to Check a Specific String in a Python List
- Use the List Comprehension to Check a Specific String in a Python List
- Use the filter() Function to Get a Specific String in a Python List
- Related Article - Python String
- Related Article - Python List
- Find String in List in Python
- Use the for Loop to Find Elements From a List That Contain a Specific Substring in Python
- Use the filter() Function to Find Elements From a Python List Which Contain a Specific Substring
- Use the Regular Expressions to Find Elements From a Python List Which Contain a Specific Substring
- Related Article - Python List
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 in operator in Python
- Using list comprehension to find strings in a Python list
- Using the any() method to find strings in a list
- Finding strings in a list using the filter and lambda methods in 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, a and 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 False .
Here, ret_value is a boolean, which evaluates to True if a lies inside b , and False otherwise.
Here’s an example to demonstrate the usage of the in operator :
a = [1, 2, 3] b = 4 if b in a: print('4 is present!') else: print('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
The 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.
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)
We can also achieve the same result using a for loop and an if statement. The equivalent code using a loop is as follows:
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 False otherwise.
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, any() returns True and the first if statement is executed. If the condition does not hold for any item, any() returns 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))
We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!
Conclusion
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.
References
Python Find String in List
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
We can use Python in operator to check if a string is present in the list or not. There is also a not in operator to check if a string is not present in the list.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] # string in the list if 'A' in l1: print('A is present in the list') # string not in the list if 'X' not in l1: print('X is not present in the list')
A is present in the list X is not present in the list
Recommended Reading: Python f-strings Let’s look at another example where we will ask the user to enter the string to check in the list.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = input('Please enter a character A-Z:\n') if s in l1: print(f' is present in the list') else: print(f' is not present in the list')
Please enter a character A-Z: A A is present in the list
Python Find String in List using count()
We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.count(s) if count > 0: print(f' is present in the list for times.')
Finding all indexes of a string in the list
There is no built-in function to get the list of all the indexes of a string in the list. Here is a simple program to get the list of all the indexes where the string is present in the list.
l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' matched_indexes = [] i = 0 length = len(l1) while i < length: if s == l1[i]: matched_indexes.append(i) i += 1 print(f'is present in at indexes ')
Output: A is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5] You can checkout complete python script and more Python examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Python Check if List Contains a String
- Use the for Loop to Check a Specific String in a Python List
- Use the List Comprehension to Check a Specific String in a Python List
- Use the filter() Function to Get a Specific String in a Python List
Strings are a sequence of characters. Just like strings store characters at specific positions, we can use lists to store a collection of strings.
In this tutorial, we will get a string with specific values in a Python list.
Use the for Loop to Check a Specific String in a Python List
The for is used to iterate over a sequence in Python.
Its implementation for obtaining a string containing specific values is shown in the example below.
py_list = ['a-1','b-2','c-3','a-4'] new_list =[] for x in py_list: if "a" in x: new_list.append(x) print(new_list)
In the above code, the if statement is used inside the for loop to search for strings containing a in the list py_list . Another list named new_list is created to store those specific strings.
Use the List Comprehension to Check a Specific String in a Python List
List comprehension is a way to create new lists based on the existing list. It offers a shorter syntax being more compact and faster than the other functions and loops used for creating a list.
py_list = ['a-1','b-2','c-3','a-4'] r = [s for s in py_list if "a" in s] print(r)
In the above code, list comprehension is used to search for strings having a in the list py_list .
Note that writing the same code using other functions or loops would have taken more time, as more code is required for their implementation, but list comprehension solves that problem.
We can also use list comprehension to find out strings containing multiple specific values i.e., we can find strings containing a and b in py_list by combining the two comprehensions.
py_list = ['a-1','b-2','c-3','a-4','b-8'] q = ['a','b'] r = [s for s in py_list if any(xs in s for xs in q)] print(r)
Use the filter() Function to Get a Specific String in a Python List
The filter() function filters the given iterable with the help of a function that checks whether each element satisfies some condition or not.
It returns an iterator that applies the check for each of the elements in the iterable.
py_lst = ['a-1','b-2','c-3','a-4'] filter(lambda x: 'a' in x,py_lst) print (filter(lambda x: 'a' in x,py_lst))
Note that the above output is a filter-iterator type object since the filter() function returns an iterator instead of a list.
We can use the list() function as shown in the code below to obtain a list.
list(filter(lambda x: 'a' in x,py_lst))
In the above code, we have used filter() to find a string with specific values in the list py_list .
Related Article - Python String
Related Article - Python List
Copyright © 2023. All right reserved
Find String in List in Python
- Use the for Loop to Find Elements From a List That Contain a Specific Substring in Python
- Use the filter() Function to Find Elements From a Python List Which Contain a Specific Substring
- Use the Regular Expressions to Find Elements From a Python List Which Contain a Specific Substring
This tutorial will introduce how to find elements from a Python list that have a specific substring in them.
We will work with the following list and extract strings that have ack in them.
my_list = ['Jack', 'Mack', 'Jay', 'Mark']
Use the for Loop to Find Elements From a List That Contain a Specific Substring in Python
In this method, we iterate through the list and check whether the substring is present in a particular element or not. If the substring is present in the element, then we store it in the string. The following code shows how:
str_match = [s for s in my_list if "ack" in s] print(str_match)
The in keyword checks whether the given string, "ack" in this example, is present in the string or not. It can also be replaced by the __contains__ method, which is a magic method of the string class. For example:
str_match = [s for s in my_list if s.__contains__("ack")] print(str_match)
Use the filter() Function to Find Elements From a Python List Which Contain a Specific Substring
The filter() function retrieves a subset of the data from a given object with the help of a function. This method will use the lambda keyword to define the condition for filtering data. The lambda keyword creates a one-line lambda function in Python. See the following code snippet.
str_match = list(filter(lambda x: 'ack' in x, my_list)) print(str_match)
Use the Regular Expressions to Find Elements From a Python List Which Contain a Specific Substring
A regular expression is a sequence of characters that can act as a matching pattern to search for elements. To use regular expressions, we have to import the re module. In this method, we will use the for loop and the re.search() method, which is used to return an element that matches a specific pattern. The following code will explain how:
import re pattern=re.compile(r'ack') str_match = [x for x in my_list if re.search('ack', x)] print(str_match)
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.