607

Given a list xs and a value item, how can I check whether xs contains item (i.e., if any of the elements of xs is equal to item)? Is there something like xs.contains(item)?


For performance considerations, see Fastest way to check if a value exists in a list.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • Your question implies you're only interested in *list contains item*, not *list contains sublist? /tuple/ set/ frozenset/...?* – smci Dec 31 '19 at 16:58
  • Does this answer your question? [Fastest way to check if a value exists in a list](https://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exists-in-a-list) – starball Aug 17 '22 at 03:06

6 Answers6

1008

Use:

if my_item in some_list:
    ...

Also, inverse operation:

if my_item not in some_list:
    ...

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
defuz
  • 26,721
  • 10
  • 38
  • 60
  • 1
    With a list containing numpy arrays, will this check for numpy instances or values inside the numpy instances? – Daniel Möller Aug 18 '17 at 16:20
  • Beware ! This matches while this is very probably what you did not expect: `o='--skip'; o in ("--skip-ias"); # returns True !` – Alex F Feb 28 '18 at 10:03
  • 6
    @AlexF: That matches because `("--skip-ias")` is not a tuple, but a string (the parentheses do nothing, just like `(1)` is just an integer). If you want a 1-tuple, you need to add a comma after the single item: `("--skip-ias",)` (or `(1,)`). – Blckknght Jun 10 '18 at 08:31
  • Note that if you're comparing characters, this is case insensitive. – Tillson May 16 '19 at 02:32
71

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
>>>         
xged
  • 1,207
  • 1
  • 14
  • 20
Ant
  • 5,151
  • 2
  • 26
  • 43
7

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)

Dustin Raimondi
  • 383
  • 1
  • 4
  • 10
  • 1
    In my case i have a list of object called Category and a need it to test only for the property Link, so this solutions fits better in my case. Thanks – rodrigorf Feb 05 '18 at 18:15
  • 9
    `any(item == test_item for item in list_to_test)` would work too, I think? – somebody Apr 07 '18 at 01:16
5

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
Mr. Squig
  • 2,755
  • 17
  • 10
  • 17
    The `index` method does not return -1 if the element is not present, it throws a `ValueError` exception. – Daniel Mar 28 '15 at 05:33
1

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
Andreas
  • 8,694
  • 3
  • 14
  • 38
-1

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

rsonx
  • 436
  • 7
  • 16