+ 1

# Index Error Issue

I ran into an Index Error issue in my code and I can’t find the reason behind it. This is the code: https://code.sololearn.com/cFzyi76dj0Rw/?ref=app It should look like the following code, but including the index for each y value: https://code.sololearn.com/c8ka3We8Wc0t/?ref=app Any suggestions?

3 Answers

+ 1

When the value of "i" is 5 your "primes" list looks like this:
[1, 5, 7]
So accesing primes[5] gives you an IndexError since there are only 3 elements.
Remove line 11 and everything should work properly:
print("i: "+ str(i) + " --> " + "result: " + str(primes[i]))

0

Try this:
from math import sqrt
primes = []
def prime_gen(x):
index = 0
i = 0
while index < x:
y = sqrt(24*i+1)
int_y = int(y)
if y == int_y :
primes.append(int_y)
print(f"i: {i} -> result: {primes[index]}")
index += 1
i += 1
prime_gen(10)

0

Thanks to all