Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ==?

like image 369
ChrisB Avatar asked Aug 15 '12 14:08

ChrisB


1 Answers

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 to any, 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 means is should not be needed, really.

So, the correct spelling is:

# 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())
like image 112
Martijn Pieters Avatar answered Sep 20 '22 12:09

Martijn Pieters