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.
Advertisement
Answer
Use:
JavaScript
x
3
1
if my_item in some_list:
2
3
Also, inverse operation:
JavaScript
1
3
1
if my_item not in some_list:
2
3
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.