Sequence-length - Missing the obvious ?

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Wed May 31 05:36:18 EDT 2000


mlauer at trollinger-fe.rz.uni-frankfurt.de wrote in comp.lang.python:
> class sequence:
> 	
> 	def __getitem__( self, i ):
> 		return self.d[i]
> 
> seq = sequence()
> seq.d = "Hallo"
> 
> for item in seq:
> 	print item,
> 
> -----------------------------------
> 
> This works - gives out "H a l l o".
> __getitem__ get´s called five times.
> 
> But why ? How does the for loop knows
> how much elements the sequence contains ?
> I did not program the __len__ function,
> so... how ?

for loops just call __getitem__ with increasing i until an IndexError is
raised. This makes them really generic.

So __getitem__ is actually called six times.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
  Murphy's Rules, "Suicide on the steppes":
   The Russian Civil War was designed to simulate chaotic conditions in
   Russia in 1917. Players can get points for attacking their own units.



More information about the Python-list mailing list