For the built-in python containers (list
, tuple
, etc) the in
operator is equivalent to any(y == item for item in container)
with the caveat that the former method is faster (and prettier):
In [13]: container = range(10000)
In [14]: %timeit (-1 in container)
1000 loops, best of 3: 241 us per loop
In [15]: %timeit any(-1 == item for item in container)
1000 loops, best of 3: 1.2 ms per loop
Is there an equivalent to any(y is item for item in container)
? That is, a test that uses is
instead of ==
?
Nope, there isn't. The
is
operator is just not needed that often to justify having to maintain a C-optimized method and adding confusion to the python API.The
in
test for lists and tuples does do a full search similar toany
, albeit in C, btw. In sets however, the test makes use of the efficient storage algorithm underlying the container and the search takes constant time in the expected case. For both sets and mappings, keys are supposed to have a stable hash, which in most cases meansis
should not be needed, really.So, the correct spelling is: