[Python-ideas] Changing `Sequence.__contains__`

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Jul 21 04:06:59 CEST 2014


On 20/07/2014 23:06, Ram Rachum wrote:
> Why does the default `Sequence.__contains__` iterate through the items
> rather than use `.index`, which may sometimes be more efficient?
>
> I suggest an implementation like this:
>
>      def __contains__(self, i):
>          try: self.index(i)
>          except ValueError: return False
>          else: return True
> What do you think?
>

I don't see how that can be more efficient than the naive

def __contains__(self, i):
     for elem in self:
         if elem == i:
             return True
     return False

What am I missing?

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com




More information about the Python-ideas mailing list