[Tutor] __getitem__

Alan Gauld alan.gauld at freenet.co.uk
Tue Jan 17 00:45:51 CET 2006


> map calls, list comprehension, etc.  For loops, etc.
> work by indexing a  sequences from zero to a higher
> index until out-of-bounds is reached.  

What makes you think that?
So far as I know for loops work by calling next on 
an iterator until nothing gets returned, no indexes 
involved.(At least not in the for loop) But they could 
just as well work by calling the len() function and 
iterating that number of times. And len() could be 
stored as part of the data structure ala Pascal arrays.

The point being that it is dangerous to assume how 
a language feature works internally, it can change from 
version to version.

In this case the iterator solution means that the for 
loop can work on any iterable entity - like files for 
instance.

> But why does this work?
> 
>>>> class stepper:
> ...     def __getitem__(self, i):
> ...         return self.data[i]
> ...
>>>> 'p' in X
> True
> 
> What does 'in' have to do with indexing?

Nothing unless its implementation uses a while loop
and index, but thats unlikely.

But your code doesn't show what X is, I assume its 
an instance of stepper? (The convention is for uppercase 
class names and lower case object names so I'm slightly 
unsure about that assumption!) But we don't even have 
the whole of stepper since there is no self.data definition.
Its kind of hard to say.

I'm slightly confused by the question, sorry.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list