printing a list of values within a certain range

Viewed 41

So I am having a problem with printing certain values that fall within a certain range from a list

Here is the code

import statistics as st

players = [180, 172, 178, 185, 190, 195, 192, 200, 210, 190]
players.sort()


avg = sum(players)/ len(players)


std = st.stdev(players)


low = avg - std
high = avg + std

for i in range (int(low), int(high)):
 print(players[i])

It is giving me this error

Traceback (most recent call last):
File "file0.py", line 16, in <module>
print(players[i])
IndexError: list index out of range

Thank you

2 Answers

The mistake in your loop is that, you are trying to access the value at an index which is beyond your loop. Instead of accessing value at indices [int(low), int(high)), you can add an if case to check if the value lies in that range and print it.

Your intended (more pythonic) solution is

print([x for x in players if low < x < high])

Edit : Suggested by @Barmar and @OlvinRoght

Your code at the moment is returning players at position index i (players[i]), and your i values here the numbers between your low and high variables.

Since these variables are larger than the length of your list, you are trying to index your list players with numbers that are too large, meaning you are returned the "IndexError: list index out of range" error.

Try instead:

print([player for player in players if player >int(low) and player < int(high)])

using list comprehension or:

for player in players:
    if player > int(low) and player < int(high):
        print(player)

using a classic for loop.

Related