This tutorial will discuss about a unique way to check if any element in list starts with string in Python.
Suppose we have a list of strings and a separate prefix string, and we want to check if any string in the list starts with the given prefix string or not. For this, we can use the any()
function.
The any()
method accepts a sequence as an argument, and returns True
if any element in the sequence evaluates to True
.
So, we can use a for loop in a generator expression and call the startswith() function on each item of the list. It will return a boolean list, where each True value indicated that the corresponding string in the list starts with the given prefix string i.e.
any(elem.startswith(strValue) for elem in listOfStrings)
It returns True, if any string element in list listOfStrings
starts with the given string i.e. strValue
.
Frequently Asked:
Example 1
Let’s see the complete example,
# Example 1 listOfStrings = ['That', 'Where', 'Why', 'This', 'Now', 'Here'] strValue = 'No' # Check if any element in list starts with the given string if any(elem.startswith(strValue) for elem in listOfStrings): print('Yes, an element from List starts with the given string') else: print('None of the element from List starts with the given string')
Output
Yes, an element from List starts with the given string
Example 2
Let’s see the complete example,
listOfStrings = ['That', 'Where', 'Why', 'This', 'Now', 'Here'] strValue = 'Ho' # Check if any element in list starts with the given string if any(elem.startswith(strValue) for elem in listOfStrings): print('Yes, an element from List starts with the given string') else: print('None of the element from List starts with the given string')
Output
Latest Python - Video Tutorial
None of the element from List starts with the given string
Summary
We learned how to check if any string in list starts with a given prefix string in Python. Thanks.
Latest Video Tutorials