How does "for" work?
Steve Juranich
sjuranic at condor.ee.washington.edu
Tue Oct 10 14:07:06 EDT 2000
I have an object that is actually just a list of other, smaller items.
In the list object, I have overridden __getitem__ to be the following:
def __getitem__(self, key):
return self.data[key]
This should be straightforward enough. But when I try something like:
for item in list:
# Whatever
I get a complaint once the for loop gets to the end of the list about a
KeyError. The length of the list is 5176 (in this case going from 0-5175).
But the for loop tries to get list[5176]. Why does this happen? How does
"for" know how long the list is? Is the problem in my __len__ function or
in my __getitem__ function? If I just change __getitem__ to return the
key-1th entry of the list, will that fix it?
BTW, I should mention that __len__() for the list looks like this:
def __len__(self):
return len(self.data)
Where data is a dictionary of the smaller items, with a time index (by ints)
being used as the key.
Thanks so much for the help.
----------------------------------------------------------------------
Stephen W. Juranich sjuranic at ee.washington.edu
Electrical Engineering http://students.washington.edu/sjuranic
University of Washington http://rcs.ee.washington.edu/ssli
More information about the Python-list
mailing list