Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading