pythonlistfor-loopindex-error

Python: IndexError: list index out of range – trying to count two numbers from list in a for loop


I´m trying to write a code in python, that should make an arithmetic average from a numbers in list – The user inputs numbers that are converted into the list as integers, then I use for loop to count the amount of numbers in list, this I save to variable, after that I want to create another for loop that will add the numbers together so I can divide them after with a variable a mentioned before. The result should be printed.

The Code:

student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])

pomocna = 0
soucet = 0
pomocnaj = 0

for i in student_heights:
    pomocna += 1

for j in student_heights:
    if  pomocnaj == 0 and j == 0:
        pass
    else:
        soucet = soucet +(student_heights[j] + student_heights[pomocnaj]) 
        pomocnaj += 1

print(soucet/pomocna)

The Error:

Input a list of student heights 123 156 189
Traceback (most recent call last):
  File "main.py", line 20, in <module>
    soucet = soucet +(student_heights[j] + student_heights[pomocnaj]) 
IndexError: list index out of range

I was expecting that the number on index 1 will be added up together with number on index 0 – the for loop will repeat until the end of the list, then I print the variable "soucet".

The if statement is there just to make loop run without adding the numbers together, which would be number on index 0 and number on index 0, so I made statement if pomocnaj == 0 and j == 0 pass and repeat, now j = 1 and pomocnaj equals 0 so numbers on index 1 and index 0 will be added up together.


Solution

  • for j in student_heights:
    

    This loops over the values in the list, not the indexes.

    So, inside this loop where you try to access student_heights[j], j is the actual height value.

    So if the first height in the list was, say, 100, this code would try to access student_heights[100], which is the error.