You are not logged in.

#1 2010-01-01 12:41:18

baion baion
Member
From: Nicosia, Cyprus
Registered: 2009-06-13
Posts: 48

[Solved] Help me with Python IndexError

Hello all and Happy New Year,
I have started learning python and I thought I would develop a program to find the modal class from a list of numbers. The modal class is the most frequent number in a list of numbers. My code is the following, (I leave out parts that are irrelevant to the problem and include only the part that calculates how frequent each number is):

# Find how frequently each number occurs, this only works with a sorted list
freqidx = []
freq = []
loopcount = 0
numbercount = 0
prevnumber = None
for number in numbers:
    if number == prevnumber:
        freq[loopcount] +=1
    else:
        freqidx.append(numbercount)
        freq.append(1)
        loopcount += 1
    prevnumber = number
    numbercount += 1

The numbers list was populated and sorted in ascending order earlier in the program so don't let that confuse you.
Now when I run the program I get the error:

Traceback (most recent call last):
  File "Mode.py", line 54, in <module>
    freq[loopcount] +=1
IndexError: list index out of range

line 54 is as you can see the suite of the if statement freq[loopcount] += 1. Does anyone know why this happens? The only thing that I could think was that the very first the for loop is run the freq list is empty and thus the error is produced but the very first time the for loop is run the if statement should be false thus the else statement should be executed instead. If I add a number in the freq list, the error is not produced, which is confusing.
Any help is appreciated.

Last edited by baion baion (2010-01-01 16:59:12)

Offline

#2 2010-01-01 12:56:33

chpln
Member
From: Australia
Registered: 2009-09-17
Posts: 361

Re: [Solved] Help me with Python IndexError

Remembering lists in python are zero-indexed, you can see on the first iteration that the loopcount does not reflect the length of freq:

baion baion wrote:
freq.append(1)
loopcount += 1

freq will have a single element (i.e., an element at freq[0]), while loopcount will be 1.  At the point you attempt to modify the count

freq[loopcount] +=1

loopcount will always exceed the length of the freq by 1, hence the IndexError.

The simplest adjustment would be to initialise `loopcount' to -1.

Last edited by chpln (2010-01-01 12:58:52)

Offline

#3 2010-01-01 13:33:19

baion baion
Member
From: Nicosia, Cyprus
Registered: 2009-06-13
Posts: 48

Re: [Solved] Help me with Python IndexError

Thank you very much for pointing out a rather dumb mistake. It works like a charm now. big_smile

Offline

Board footer

Powered by FluxBB