Fix Python – Is there a short contains function for lists?

Question

Asked By – Joan Venge

How do I check if a list xs contains an item?

if xs.contains(item):
    ...

Now we will see solution for issue: Is there a short contains function for lists?


Answer

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.

This question is answered By – defuz

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0