Do python lists have an equivalent for __contains__ that validates identity?

For built-in python containers ( list , tuple , etc.), the in operator is equivalent to any(y == item for item in container) with a warning that the previous 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 any equivalent of any(y is item for item in container) ? That is, a test that uses is instead of == ?

+8
python identity
source share
1 answer

No no. The is operator is simply not needed, which often justifies the need to support a C-optimized method and add confusion to the python API.

The in test for lists and tuples performs a full search, similar to any , albeit in C, btw. However, the tests use the efficient storage algorithm underlying the container, and the search requires constant time in the expected case. For both sets and mappings, the keys must have a stable hash, which in most cases means that is not required, really.

So, the correct spelling:

 # For sequences any(y is item for item in container) # For sets, short circuit first for the not-present case: # (note that you normally should not need this as you are supposed to rely on the hash) y in setcontainer and any(y is item for item in setcontainer) # For mappings, y is a key y in mapping # For mappings, y is a value, and you do not have a key, fall back to any any(y is item for item in mapping.itervalues()) 
+6
source share

All Articles