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
.
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
Frequently Asked:
- Convert a number to a list of integers in Python
- Remove all elements from a Python List
- Print all items in a List with a delimiter in Python
- Python : How to remove multiple elements from list ?
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
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.