[Python-ideas] Changing `Sequence.__contains__`

Chris Angelico rosuav at gmail.com
Mon Jul 21 04:09:27 CEST 2014


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


More information about the Python-ideas mailing list