1
def mode(given_list):
    highest_list = []
    highest = 0
    index = 0
    for x in range(0, len(given_list)):
        occurrences = given_list.count(given_list[x])
        if occurrences > highest:
            highest = occurrences
            highest_list[0] = given_list[x]
        elif occurrences == highest:
            highest_list.append(given_list[x])

The code is meant to work out the mode of a given list. I do not understand where I am going wrong.

Exact Error I am receiving.

line 30, in mode
    highest_list[0] = given_list[x]
IndexError: list assignment index out of range

3 Answers 3

1

The problem is that you have an empty list originally:

highest_list = []

And then in the loop you try to access it at index 0:

highest_list[0] = ...

It's impossible, because it's an empty list and so is not indexable at position 0.

A better way to find the mode of a list is to use a collections.Counter object:

>>> from collections import Counter
>>> L = [1,2,3,3,4]
>>> counter = Counter(L)
>>> max(counter, key=counter.get)
3
>>> [(mode, n_occurrences)] = counter.most_common(1)
>>> mode, n_occurrences
(3, 2)
Sign up to request clarification or add additional context in comments.

Comments

1

As far as getting the mode, you can just use a Counter from the collections library

from collections import Counter
x = [0, 1, 2, 0, 1, 0] #0 is the mode
g = Counter(x)
mode = max(g, key = lambda x: g[x])

1 Comment

You can use g.get instead of lambda x: g[x].
0

At that point, at the start of the loop, highest_list is empty, so there's no first index. You can initialize highest_list as [0] so that there is always at least one "highest value."

That said, you can accomplish this more simply as follows:

def mode(given_list):
    return max(set(given_list), key=given_list.count)

This will find the highest item in the passed given_list, based on each item's count() in it. Making a set first ensures that each item is only counted once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.