0
lst = [3, 4, 3, 5, 3]

def lstmaker(lst):
   lst1 = []
   x = 0
   while x < len(lst): 
        if lst[x] == lst[x+1]:
            lst1.append(lst[x])
        else:
            pass
        x+=1
   print lst1
lstmaker(lst)

I tried to make this simple program to find the the mode of list, but it just throws the index of out range error.

Thanks

jeremy
  • 307
  • 4
  • 15
Jacob Platin
  • 145
  • 2
  • 15
  • When `lst[x]` is the last element of the list, `lst[x+1]` is outside the list. – Barmar Mar 03 '15 at 00:50
  • Even if you solve the indexing problem, your code doesn't seem to have anything to do with finding the mode. All it does is make a new list containing all the elements that are equal to the element after them. – Barmar Mar 03 '15 at 00:54

2 Answers2

2

For the last value of x, lst[x+1] x+1 is out of range. The while loop should be while x < len(lst) -1.

As a side note, to calculate the mode, you can simply do: max(set(lst), key=lst.count) as shown here.

Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294
1

The logic is incorrect.

For starters, the reason you're getting an index out of range issue is because of the line

if lst[x] == lst[x+1]

x is correctly incremented throughout your loop, but when x is at the last index, that +1 bit accesses an index that isn't in the list (e.g. index 5 of a list of size 5).

Additionally, what you were actually doing within the loop doesn't appear to be getting you towards a value for the mode. The mode is the element(s) in a list that occurs the most. One approach to tackling this problem could be using a dictionary (dict()) where the "keys" are the elements in your list, and the "values" are the amount of times each element occurs.

Try something like this:

# lst defined up here
occurrences = dict()
for x in lst:
    if x in occurrences:
        occurrences[x] += 1
    else:
        occurrences[x] = 1

mode = occurrences.keys()[0]
for k in occurrences:
    if occurrences[k] >= mode:
        mode = k
print(mode) # or return, etc.

This is perhaps not the most "Pythonic" solution, though it is an intuitive break-down of the logic involved in finding the mode, at least as if you were to do it by hand on paper.

Chris Sprague
  • 740
  • 1
  • 12
  • 22