I have something like this:
extensionsToCheck = ['.pdf', '.doc', '.xls']
for extension in extensionsToCheck:
if extension in url_string:
print(url_string)
I am wondering what would be the more elegant way to do this in Python (without using the for loop)? I was thinking of something like this (like from C/C++), but it didn’t work:
if ('.pdf' or '.doc' or '.xls') in url_string:
print(url_string)
Edit: I’m kinda forced to explain how this is different to the question below which is marked as potential duplicate (so it doesn’t get closed I guess).
The difference is, I wanted to check if a string is part of some list of strings whereas the other question is checking whether a string from a list of strings is a substring of another string. Similar, but not quite the same and semantics matter when you’re looking for an answer online IMHO. These two questions are actually looking to solve the opposite problem of one another. The solution for both turns out to be the same though.
asked Jun 30, 2011 at 7:41
tkittkit
7,8246 gold badges40 silver badges70 bronze badges
2
Use a generator together with any
, which short-circuits on the first True:
if any(ext in url_string for ext in extensionsToCheck):
print(url_string)
EDIT: I see this answer has been accepted by OP. Though my solution may be «good enough» solution to his particular problem, and is a good general way to check if any strings in a list are found in another string, keep in mind that this is all that this solution does. It does not care WHERE the string is found e.g. in the ending of the string. If this is important, as is often the case with urls, you should look to the answer of @Wladimir Palant, or you risk getting false positives.
Nam G VU
32.6k68 gold badges227 silver badges369 bronze badges
answered Jun 30, 2011 at 8:00
8
extensionsToCheck = ('.pdf', '.doc', '.xls')
'test.doc'.endswith(extensionsToCheck) # returns True
'test.jpg'.endswith(extensionsToCheck) # returns False
answered Jun 30, 2011 at 7:57
eumiroeumiro
204k34 gold badges297 silver badges261 bronze badges
5
It is better to parse the URL properly — this way you can handle http://.../file.doc?foo
and http://.../foo.doc/file.exe
correctly.
from urlparse import urlparse
import os
path = urlparse(url_string).path
ext = os.path.splitext(path)[1]
if ext in extensionsToCheck:
print(url_string)
answered Jun 30, 2011 at 7:57
Wladimir PalantWladimir Palant
56.5k12 gold badges98 silver badges125 bronze badges
Just in case if anyone will face this task again, here is another solution:
extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'file.doc'
res = [ele for ele in extensionsToCheck if(ele in url_string)]
print(bool(res))
> True
answered Apr 13, 2021 at 7:54
AidosAidos
7297 silver badges20 bronze badges
Use list comprehensions if you want a single line solution. The following code returns a list containing the url_string when it has the extensions .doc, .pdf and .xls or returns empty list when it doesn’t contain the extension.
print [url_string for extension in extensionsToCheck if(extension in url_string)]
NOTE: This is only to check if it contains or not and is not useful when one wants to extract the exact word matching the extensions.
answered Apr 25, 2016 at 17:15
psunpsun
60510 silver badges13 bronze badges
2
This is a variant of the list comprehension answer given by @psun.
By switching the output value, you can actually extract the matching pattern from the list comprehension (something not possible with the any()
approach by @Lauritz-v-Thaulow)
extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'http://.../foo.doc'
print([extension for extension in extensionsToCheck if(extension in url_string)])
[‘.doc’]`
You can furthermore insert a regular expression if you want to collect additional information once the matched pattern is known (this could be useful when the list of allowed patterns is too long to write into a single regex pattern)
print([re.search(r'(w+)'+extension, url_string).group(0) for extension in extensionsToCheck if(extension in url_string)])
['foo.doc']
answered Nov 8, 2016 at 18:02
DannidDannid
1,4491 gold badge19 silver badges17 bronze badges
2
Check if it matches this regex:
'(.pdf$|.doc$|.xls$)'
Note: if you extensions are not at the end of the url, remove the $
characters, but it does weaken it slightly
answered Jun 30, 2011 at 7:46
3
This is the easiest way I could imagine
list_ = ('.doc', '.txt', '.pdf')
string = 'file.txt'
func = lambda list_, string: any(filter(lambda x: x in string, list_))
func(list_, string)
# Output: True
Also, if someone needs to save elements that are in a string, they can use something like this:
list_ = ('.doc', '.txt', '.pdf')
string = 'file.txt'
func = lambda list_, string: tuple(filter(lambda x: x in string, list_))
func(list_, string)
# Output: '.txt'
answered Jan 10 at 13:28
LevinsonLevinson
1111 silver badge4 bronze badges
We are given a String and our task is to test if the string contains elements from the list.
Example:
Input: String: Geeks for Geeks is one of the best company. List: ['Geeks', 'for'] Output: Does string contain any list element : True
Naive Approach checking each word in the string
Here we are splitting the string into list of words and then matching each word of this list with the already present list of words we want to check.
Python3
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
test_string
=
test_string.split(
" "
)
flag
=
0
for
i
in
test_string:
for
j
in
test_list:
if
i
=
=
j:
flag
=
1
break
if
flag
=
=
1
:
print
(
"String contains the list element"
)
else
:
print
(
"String does not contains the list element"
)
Output:
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] String contains the list element
Using list comprehension to check if string contains element from list
This problem can be solved using the list comprehension, in this, we check for the list and also with string elements if we can find a match, and return true, if we find one and false is not using the conditional statements.
Python3
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
[ele
for
ele
in
test_list
if
(ele
in
test_string)]
print
(
"Does string contain any list element : "
+
str
(
bool
(res)))
Output:
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Using any() to check if string contains element from list
Using any function is the most classical way in which you can perform this task and also efficiently. This function checks for match in string with match of each element of list.
Python3
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
any
(ele
in
test_string
for
ele
in
test_list)
print
(
"Does string contain any list element : "
+
str
(res))
Output:
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Using find() method to check if string contains element from list
Here we are using the find() method to check the occurrence of the word and it returns -1 if the word does not exist in the list.
Python3
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
False
c
=
0
for
i
in
test_list:
if
(test_string.find(i)!
=
-
1
):
c
+
=
1
if
(c>
=
1
):
res
=
True
print
(
"Does string contain any list element : "
+
str
(
bool
(res)))
Output:
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Using Counter() function
Python3
from
collections
import
Counter
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
False
freq
=
Counter(test_list)
for
i
in
test_string.split():
if
i
in
freq.keys():
res
=
True
print
(
"Does string contain any list element : "
+
str
(
bool
(res)))
Output
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Time Complexity: O(N)
Auxiliary Space: O(N)
Using Set Intersection to Check if String Contains Element from List
One approach to check if a string contains an element from a list is to convert the string and the list into sets and then check for the intersection between the sets. If the intersection is not an empty set, it means that the string contains an element from the list.
Python3
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string:"
, test_string)
print
(
"The original list:"
, test_list)
string_set
=
set
(test_string.split())
list_set
=
set
(test_list)
if
list_set.intersection(string_set):
print
(
"String contains an element from the list"
)
else
:
print
(
"String does not contain an element from the list"
)
Output
The original string: There are 2 apples for 4 persons The original list: ['apples', 'oranges'] String contains an element from the list
This approach has a time complexity of O(n) and an auxiliary space of O(n).
Using operator.countOf() method.
Python3
import
operator as op
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
False
c
=
0
for
i
in
test_list:
if
(op.countOf(test_string, i)
=
=
0
):
c
+
=
1
if
(c >
=
1
):
res
=
True
print
(
"Does string contain any list element : "
+
str
(
bool
(res)))
Output
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Using operator.contains() method
Approach
- Initiate a for loop to traverse list of strings and set res to False
- Check whether each string of list is present in given string
- If yes set res to True and break out of for loop
- Display res
Python3
import
operator as op
test_string
=
"There are 2 apples for 4 persons"
test_list
=
[
'apples'
,
'oranges'
]
print
(
"The original string : "
+
test_string)
print
(
"The original list : "
+
str
(test_list))
res
=
False
c
=
0
for
i
in
test_list:
if
(op.contains(test_string, i)):
res
=
op.contains(test_string, i)
break
print
(
"Does string contain any list element : "
+
str
(res))
Output
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Time Complexity : O(M*N) M-length of test_list N-length of test_string
Auxiliary Space : O(1)
Introduction
In this tutorial, we’ll take a look at how to check if a list contains an element or value in Python. We’ll use a list of strings, containing a few animals:
animals = ['Dog', 'Cat', 'Bird', 'Fish']
Check if List Contains Element With for Loop
A simple and rudimentary method to check if a list contains an element is looping through it, and checking if the item we’re on matches the one we’re looking for. Let’s use a for
loop for this:
for animal in animals:
if animal == 'Bird':
print('Chirp!')
This code will result in:
Chirp!
Check if List Contains Element With in Operator
Now, a more succinct approach would be to use the built-in in
operator, but with the if
statement instead of the for
statement. When paired with if
, it returns True
if an element exists in a sequence or not. The syntax of the in
operator looks like this:
element in list
Making use of this operator, we can shorten our previous code into a single statement:
if 'Bird' in animals: print('Chirp')
This code fragment will output the following:
Chirp
This approach has the same efficiency as the for
loop, since the in
operator, used like this, calls the list.__contains__
function, which inherently loops through the list — though, it’s much more readable.
Check if List Contains Element With not in Operator
By contrast, we can use the not in
operator, which is the logical opposite of the in
operator. It returns True
if the element is not present in a sequence.
Let’s rewrite the previous code example to utilize the not in
operator:
if 'Bird' not in animals: print('Chirp')
Running this code won’t produce anything, since the Bird
is present in our list.
But if we try it out with a Wolf
:
if 'Wolf' not in animals: print('Howl')
This code results in:
Howl
Check if List Contains Element With Lambda
Another way you can check if an element is present is to filter out everything other than that element, just like sifting through sand and checking if there are any shells left in the end. The built-in filter()
method accepts a lambda function and a list as its arguments. We can use a lambda function here to check for our 'Bird'
string in the animals
list.
Then, we wrap the results in a list()
since the filter()
method returns a filter
object, not the results. If we pack the filter
object in a list, it’ll contain the elements left after filtering:
retrieved_elements = list(filter(lambda x: 'Bird' in x, animals))
print(retrieved_elements)
This code results in:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
['Bird']
Now, this approach isn’t the most efficient. It’s fairly slower than the previous three approaches we’ve used. The filter()
method itself is equivalent to the generator function:
(item for item in iterable if function(item))
The slowed down performance of this code, amongst other things, comes from the fact that we’re converting the results into a list in the end, as well as executing a function on the item on each iteration.
Check if List Contains Element Using any()
Another great built-in approach is to use the any()
function, which is just a helper function that checks if there are any (at least 1) instances of an element in a list. It returns True
or False
based on the presence or lack thereof of an element:
if any(element in 'Bird' for element in animals):
print('Chirp')
Since this results in True
, our print()
statement is called:
Chirp
This approach is also an efficient way to check for the presence of an element. It’s as efficient as the first three.
Check if List Contains Element Using count()
Finally, we can use the count()
function to check if an element is present or not:
list.count(element)
This function returns the occurrence of the given element in a sequence. If it’s greater than 0, we can be assured a given item is in the list.
Let’s check the results of the count()
function:
if animals.count('Bird') > 0:
print("Chirp")
The count()
function inherently loops the list to check for the number of occurrences, and this code results in:
Chirp
Conclusion
In this tutorial, we’ve gone over several ways to check if an element is present in a list or not. We’ve used the for
loop, in
and not in
operators, as well as the filter()
, any()
and count()
methods.
In this tutorial, you’ll learn how to use Python to check if a list contains an item. Put differently, you’ll learn if an item exists in a Python list. Being able to determine if a Python list contains a particular item is an important skill when you’re putting together conditional expressions. For example, if you’re developing a web application, you may want to see if a user has already selected a number of values. Otherwise, if you’re developing a game, you may want to see if a user has different items in their inventory.
By the end of having read this tutorial, you’ll have learned how to check for membership in a list. You’ll learn how to do this using the in
keyword, as well as checking if an item doesn’t exist in a Python list using the not in
keywords. You’ll also learned how to check if a list contain an item using the Python any()
function, as well as the count()
function. Finally, you’ll learn some naive implementations of checking membership in a list, such as for-loops and list comprehensions.
The Quick Answer: Use in
To Check if a Python List Contains an Item
One of the easiest and most Pythonic ways to check for membership in a Python list is to use the in
key. Technically, the in
keyword serves two purposes:
- To check for membership in a list, and
- To loop over a items in a for loop
In this case, we’ll use the in
keyword to check if an item exists in a list. This provides a readable and almost plain-English way to check for membership. Let’s see what this looks like:
# Check if a Python List Contains an Item
items = ['datagy', 'apples', 'bananas']
if 'datagy' in items:
print('Item exists!')
# Returns: Item exists
We can that by writing if 'item' in items
, we’re able to evaluate if something exists in our list. This is a really intuitive way to check if items exist or not.
In the next section, you’ll learn how to use Python to check if an item doesn’t exist.
Need to replace an item in a list? Check out my tutorial on this topic here: Python: Replace Item in List (6 Different Ways)
Check if a Python List Doesn’t Contain an Item Using not in
In this section, you’ll learn to check if a list doesn’t contain an item. We can do this by negating the in
keyword, using the not
keyword. Similar to the example above, this reads like relatively plain English. Let’s see how we can use the not in
keyword to see if an item isn’t a list:
# Check if a Python List Doesn't Contain an Item
items = ['datagy', 'apples', 'bananas']
if 'oranges' not in items:
print("Item doesn't exists!")
# Returns: Item doesn't exist!
We can see that the not in
keyword allows us to determine if an item doesn’t exist. It returns the opposite truthiness of the in
keyword. Because of this, it allows us to write cleaner code.
In the next section, you’ll learn to check for membership in a Python list using the .count()
method.
Need to remove an item for a list? Check out my tutorial to learn how to here: Remove an Item from a Python List (pop, remove, del, clear)
Check if a Python List Contains an Item Using count
Python lists come with a number of different helpful methods. One of these methods is the .count()
method, which counts the number of times an item appears in a list. Because of this, we can see if an item exists in a list if the count of that item is anything greater than 0. If the count is 0, then the item doesn’t exist in our list.
Let’s see what this looks like:
# Check if a Python List Contains an Item using .count()
items = ['datagy', 'apples', 'bananas']
if items.count('datagy') > 0:
print('Item exists!')
# Returns: Item exists!
If any item exists, the count will always be greater than 0. If it doesn’t, the count will always be 0.
We can combine this if statement into a single line as well. Let’s see what this looks like:
# Check if a Python List Contains an Item using .count()
items = ['datagy', 'apples', 'bananas']
print('Exists') if items.count('datagy') else print("Doesn't exist")
# Returns: Exists
The expression here works like the Python ternary operator. If you want to learn more about how the Python ternary operator works, check out my in-depth guide on the ternary operator here.
In the next section, you’ll learn how to use the any()
function to check for membership in a Python list.
Want to learn how to shuffle a list? Check out my tutorial here: Python: Shuffle a List (Randomize Python List Elements)
Check if a Python List Contains an Item Using any
The Python any
function scans an iterable and returns True
if any of the items in the iterable are True
. So, how can we use the any
function to check for membership in a Python list? We can place a comprehension inside the any
function to check for membership. If any item is returned, the any
function will return True
.
Let’s see what this looks like and then dive into how this works:
# Check if a Python List Contains an Item using any()
items = ['datagy', 'apples', 'bananas']
print(any(item=='datagy' for item in items))
# Returns: True
The way that this works is that the comprehension will loop over each item in the list and check if the item is equal to the one we want to check for. If it is, the comprehension returns True
for that item. Otherwise, it’ll return False
. Because of this, if a True
value exists, the any
function will return True
.
In the next section, you’ll learn how to use a for loop to check if an item exists in a list.
Want to learn how to check the length of a Python list? Learn all you need to know with this tutorial that covers five different ways to check the length: Python List Length or Size: 5 Ways to Get Length of List
Check if a Python List Contains an Item Using a For Loop
In this final section, you’ll learn how to use a for loop to check for membership in a list. We can loop over each item in our list and see if the item matches we want to check. Once the item is found, the for loop sets a value to True
and the for loop breaks.
Let’s see what this looks like in Python:
# Check if a Python List Contains an Item using a for loop
items = ['datagy', 'apples', 'bananas']
exists = False
for item in items:
if item == 'datagy':
exists = True
break
print(exists)
# Returns: True
Let’s break down what we did here:
- We created our list and a variable,
exists
, which is set toFalse
by default - We loop over every item in the list and see if it equal to the value we want to check membership for
- If the item is equal to the one we want to check for, then we set
exists
toTrue
and break the for loop
Need to remove duplicate items from a Python list? This tutorial will teach you seven different ways to do this: Python: Remove Duplicates From a List (7 Ways)
Conclusion
In this tutorial, you learned how to check for membership in a Python list, meaning checking whether an item exists. You learned how to do this using the in
keyword. You then learned how to check whether an item doesn’t exist, using the not in
keyword. You then learned other methods to check for membership, using the any
function, the .count
method, and a Python for loop.
To learn more about the Python in
keyword, check out the official documentation here. The official documentation for the any
function can be found here and for the .count
method, it can be found here.
In this article, we’ll take a look at how we can find string in 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')
Output
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)
Output
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.
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)
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.
Output
'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))
Output
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
- JournalDev article on finding a string in a List
- StackOverflow question on finding a string inside a List