How does "for" work?
Alex Martelli
aleaxit at yahoo.com
Wed Oct 11 04:06:09 EDT 2000
"Steve Juranich" <sjuranic at condor.ee.washington.edu> wrote in message
news:Pine.SOL.3.96.1001010105911.8470C-100000 at condor.ee.washington.edu...
> 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]
[snip]
> Where data is a dictionary of the smaller items, with a time index (by
ints)
> being used as the key.
I see that other posts have already remarked that you need to
change the KeyError exception (returned by addressing the self.data
dictionary with a missing key) into an IndexError (which is what
a sequence returns, and for expects), but I'd like to understand
better what you're doing. _Why_ is self.data a dictionary at all,
rather than a list? Using it correctly with a for-loop requires
that the keys be a compact set of integers from 0 upwards -- and
in this case, what do you gain by making it a dictionary rather
than a list in the first place?
Alex
More information about the Python-list
mailing list