checking if an object IS in a list

Peter Otten __peter__ at web.de
Fri Jul 18 07:13:18 EDT 2008


nicolas.pourcelot at gmail.com wrote:

> In fact, 'any(myobject is element for element in mylist)' is 2 times
> slower than using a for loop, and 'id(myobject) in (id(element) for
> element in mylist)' is 2.4 times slower.
 
This is not a meaningful statement unless you at least qualify with the
number of item that are actually checked. For sufficently long sequences
both any() and the for loop take roughly the same amount of time over here.

$ python -m timeit -s"items=range(1000); x = 1000" "any(x is item for item
in items)"
1000 loops, best of 3: 249 usec per loop
$ python -m timeit -s"items=range(1000); x = 1000" "for item in items:" " 
if x is item: break"
1000 loops, best of 3: 276 usec per loop

$ python -m timeit -s"items=range(1000); x = 0" "any(x is item for item in
items)"
100000 loops, best of 3: 3 usec per loop
$ python -m timeit -s"items=range(1000); x = 0" "for item in items:" "  if x
is item: break"
1000000 loops, best of 3: 0.317 usec per loop


Peter

PS: Take these numbers with a grain of salt, they vary a lot between runs.



More information about the Python-list mailing list