[Python-ideas] Changing `Sequence.__contains__`

Mark Lawrence breamoreboy at yahoo.co.uk
Mon Jul 21 04:36:52 CEST 2014


On 21/07/2014 03:09, Chris Angelico wrote:
> On Mon, Jul 21, 2014 at 12:06 PM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
>> 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?
>
> If your sequence provides a more efficient index(), then __contains__
> can take advantage of it. If not, it's a bit more indirection and the
> same result.
>
> ChrisA
>

The question was about the default sequence.__contains__, not mine or 
any other sequence which may or may not provide a more efficient index().

-- 
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