Is there a short contains function for lists?
PythonListSearchCollectionsContainsPython Problem Overview
I see people are using any
to gather another list to see if an item exists in a list, but is there a quick way to just do something like this?
if list.contains(myItem):
# do something
Python Solutions
Solution 1 - Python
You can use this syntax:
if myItem in some_list:
# do something
Also, inverse operator:
if myItem not in some_list:
# do something
It works fine for lists, tuples, sets and dicts (check keys).
Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.
Solution 2 - Python
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
Solution 3 - Python
I came up with this one liner recently for getting True
if a list contains any number of occurrences of an item, or False
if it contains no occurrences or nothing at all. Using next(...)
gives this a default return value (False
) and means it should run significantly faster than running the whole list comprehension.
list_does_contain = next((True for item in list_to_test if item == test_item), False)
Solution 4 - Python
The list method index
will return -1
if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if
statement you can do the following:
if myItem in list:
#do things
You can also check if an element is not in a list with the following if statement:
if myItem not in list:
#do things
Solution 5 - Python
There is also the list method:
[2, 51, 6, 8, 3].__contains__(8)
# Out[33]: True
[2, 51, 6, 3].__contains__(8)
# Out[33]: False
Solution 6 - Python
There is one another method that uses index
. But I am not sure if this has any fault or not.
list = [5,4,3,1]
try:
list.index(2)
#code for when item is expected to be in the list
print("present")
except:
#code for when item is not expected to be in the list
print("not present")
Output:
> not present