Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting this Index out of range error?

Tags:

python

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?

like image 949
Hashim Bin Talha Avatar asked Apr 14 '21 06:04

Hashim Bin Talha


1 Answers

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.

like image 160
timgeb Avatar answered Sep 28 '22 03:09

timgeb