Why I think range is a wart.

Daniel Dittmar daniel.dittmar at sap.com
Wed Mar 13 11:17:51 EST 2002


> for index in range(len(mylist)):
>     <whatever>

several solutions:

# if whatever contains only refs to mylist [index]
for element in mylist:
    <whatever>

# if you really need the index
def listIndices (list):
    return range (len (list))

for index in listIndices (mylist):
    <whatever>

# my favourite
class IndexAndElement:
    def __init__ (self, list):
        self.list = list

    def __getitem__ (self, index):
        return (index, self.list [index])

for index, element in IndexAndElement (mylist):
    <whatever>

There's more than one way to heal a wart.

Daniel






More information about the Python-list mailing list