finding object using IS instead of ==
Geoff Gerrietts
geoff at gerrietts.net
Thu Aug 28 00:54:46 EDT 2003
Quoting Mark Hahn (mark at hahnca.com):
> > If I have a large collection (list, tuple, or dict) of objects,
> > can I locate one quickly that matches a given object using the IS
> > equivalence operator instead of the value == operator?
>
> Clarification: Is there a FASTER way that takes advantage of the IS
> equivalence than using the available == method. I assume the ==
> method does a linear search, except for a dict key lookup, which is
> not what I'm talking about.
>
> Obviously if two references are the same object (IS equivalent) then
> they are == also so you could find based on == and then check for
> IS, but I want something faster.
I'm not exactly sure how to answer your question. The short answer
might be "yes" but I can't produce a long answer because I'm not even
sure the short answer is right, for the question you're asking.
An example might help?
Let's say you have a large list of O objects L1:
class O:
def __init__(self, oid):
self.oid = oid
L1 = [O(oid) for oid in range(50000)]
And somehow, you have a handle to one of those O objects:
handle = L1[random.randint(0,49999)]
You can do a search to retrieve it (them) using 'is':
matches = [o for o in L1 if o is handle]
But is this useful to your specific problem domain? That's harder to
answer.
Thanks,
--G.
--
Geoff Gerrietts "That's it! I've had it with your sassy mouth!
<geoff at gerrietts net> I didn't want to do this! (Well, actually,
http://www.gerrietts.net/ I did....)" -- Mojo Jojo, "Bubblevicious"
More information about the Python-list
mailing list