? 'in' operator and fallback to __getitem__

Terry Reedy tjreedy at udel.edu
Mon May 18 15:20:29 EDT 2009


Tim Hoffman wrote:

>>>> [i for i in aa]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 3, in __getitem__
> KeyError: 0
> 
> 
> Which suggests to me there must be some sort of order of precedence
> between __contains__ and __getitem__
> and 'for' statement must change the order in some manner.

The 'in' part of for statements has nothing to do with the 'in' 
comparison operator.  For loops first look for .__iter__ and .__next__ 
and fall back to .__getitem__.




More information about the Python-list mailing list