[Tutor] List index usage: is there a more pythonesque way?

C M Caine cmcaine at googlemail.com
Mon Apr 19 00:53:03 CEST 2010

# Example data for forms and timetable:
forms = ["P7", "P8", "P9", "P10", "P11", "S7", "S8", "S9", "S10",
"S11", "IMA", "CAT", "FOR", "RLS", "EMPTY"]

timetable = ['CAT', 'P10', 'P8', 'EMPTY', 'EMPTY', 'EMPTY', 'S10',
'S8', 'IMA', 'EMPTY', 'S7', 'S10', 'P9', 'EMPTY', 'EMPTY', 'EMPTY',
'S7', 'EMPTY', 'EMPTY', 'RLS', 'FOR', 'EMPTY', 'EMPTY', 'EMPTY', 'S9',
'EMPTY', 'EMPTY', 'S8', 'IMA', 'S11', 'P8', 'EMPTY', 'IMA', 'EMPTY',
'EMPTY', 'S11', 'S11', 'EMPTY', 'EMPTY', 'EMPTY', 'P7', 'S9', 'P11',
'EMPTY', 'EMPTY', 'P9', 'EMPTY', 'EMPTY', 'P8', 'FOR', 'S10', 'S11',
'S7', 'P7', 'EMPTY', 'EMPTY', 'IMA', 'EMPTY', 'S9', 'P10', 'P11',
'CAT', 'S8', 'P9', 'RLS']

def analyseTimetable():
        "Find number of and spaces between each form."
        numDict = {}
        spaceDict = {}
        adjustedSpaceDict = {}
        for form in forms:
            numDict[form], spaceDict['1st'+form], spaceDict['nth'+form] \
                           = 0,0,0
        for i in range(len(timetable)):
            numDict[timetable[i]] += 1
            if spaceDict['1st'+timetable[i]] == 0:
                spaceDict['nth'+timetable[i]] = i
                spaceDict['nth'+timetable[i]] = i
        for form in forms:
            adjustedSpaceDict[form] = spaceDict['nth'+form] - \
        return (numDict, adjustedSpaceDict)

# End example

This function works fine, but I think that using range(len(timetable))
is clumsy. On the other hand, I need the indexes to track the number
of spaces between instances of each form. Without using another loop
(so not using list.index), is there a way of getting the index of the
list entries?

Thanks in advance,
Colin Caine

More information about the Tutor mailing list