Daria Ivanova Daria Ivanova - 3 months ago 8
Python Question

lndexError: list index out of range

I need to generate a string from random letters given in list take_from. The first time the function was executed it generated a phrase but all my following tries prompted an error "list index out of range". I can`t understand this error in my case and I tried while loop instead of for loop but it did not work either.

from random import randint

def make_a_phrase():
random_string = ''
take_from = ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','v','u','w','x',
'y','z',' ']
for i in range(28):
random_string = random_string + take_from[randint
(0,len(take_from))]
return random_string

Answer

In Python, lists are indexed with integers ranging from 0 to 1 less than the length of the list. E.g., a list with 10 items in it would have indexes from 0 to 9.

Your call to randint() attempts to get indexes from zero to the full length of the list, which will cause this exception. Change it to:

for i in range(28):
    random_string = random_string + take_from[randint
                                    (0,len(take_from)-1)]