for iteration

Peter Otten __peter__ at web.de
Fri Aug 22 16:55:12 EDT 2003


Franck Bui-Huu wrote:

> Hello,
> 
> I'm trying to customize a list by overriding __getitem__ method but
> this change seems to not work with for iteration.
> When I use my customized list in a for iteration, all changes made
> in __getitem__ are not take into account.
> How can I modify this behaviour ?
> 
> Thanks

For the for loop to work properly, you have to overide the __iter__()
method, e.g.:

class MyList(list):
    def __getitem__(self, index):
        """ for the sake of this example convert item to uppercase """
        return list.__getitem__(self, index).upper()
    def __iter__(self):
        """ implemented using a generator """
        for i in range(len(self)):
            yield self[i] # calls the customized __getitem__()

myList = MyList(["alpha", "beta", "gamma"])

# works with __getitem__()
for index in range(len(myList)):
    print myList[index]

print

# works with __iter__()
for item in myList:
    print item

Peter




More information about the Python-list mailing list