checking if an object IS in a list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Fri Jul 18 14:40:20 CEST 2008


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

Another possibility :-)
from itertools import imap
id(x) in imap(id, items)


>If you want efficiency you should use a dictionary instead of the list anyway:

I agree, but sometimes you have few items to look for, so building the
whole dict (that requires memory too) may be a waste of time.

In theory this may be faster to build, but in practice you need a
benchmark:
ids = set(imap(id, items))
followed by:
id(x) in ids

Bye,
bearophile



More information about the Python-list mailing list