I am a beginner at Python, and I was writing some code that would pick a random letter from a list, print it, then delete it from the list so it would not be picked again. The cycle repeats through a while loop.
import random
list = ["a", "b", "c", "d", "e", "f", "g", "h" , "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
yn = "y"
while yn == "y":
npat = random.randint(0, 25)
print(list[npat])
del list[npat]
yn = input("Again?: ")
It works fine but sometimes, the random number which is picked is shown to be outside the index range.
IndexError: list index out of range
It should work fine in my opinion but there's a problem. Can anyone point it out?
Every time you del list[npat]
, the list gets shorter. Eventually random.randint(0, 25)
gives you an index that's out of bounds.
Unrelated: list
is a bad variable name, as you are masking the list
builtin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With