What is causing the message "IndexError: list index out of range"?

Viewed 84

I am comfortable with python but I can't figure out why this error is showing up because of my code:

import random
inp = input('Enter: ')
inp = str(inp)
char = 0
key = []
list = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%&*?+-')

if inp == 'New':
    while char < len(list):
        rand = random.randint(0, len(list))
        key.append(list[rand])
        char = char + 1
print(key)

The code won't always print the list "key" and instead give me the error "IndexError: list index out of range". How do I fix this?

1 Answers

randint is inclusive, so it will include the actual value of the length of the list in the random values, which can cause out of range index. For example, if you have a list that has length 8, it can give you the value 8, even though the max index you have can only be 7.

To fix, you just need to use:

rand = random.randint(0, len(list) - 1)

EDIT:

As @DeepSpace mentioned, you can also use random.choice(list). And also try to avoid using the built-in list as a variable name.

Related