checking if an object IS in a list

Peter Otten __peter__ at web.de
Fri Jul 18 08:21:55 EDT 2008


nicolas.pourcelot at gmail.com wrote:

> On 18 juil, 13:13, Peter Otten <__pete... at web.de> wrote:
>> nicolas.pource... 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.
>>
> 
> Sorry. I used short lists (a list of 20 floats) and the element
> checked was not in the list.
> (That was the case I usually deals with in my code.)

What is your (concrete) use case, by the way?

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

$ python -m timeit -s"d=dict((id(i), i) for i in range(1000)); x =
1000" "id(x) in d"
1000000 loops, best of 3: 0.275 usec per loop

Peter



More information about the Python-list mailing list