0
for x in range (0,24):
  RandCharGen = random.randint(0,len(characters)) 
  RandChar = characters[RandCharGen]

Shows the error:

RandChar = characters[RandCharGen]
IndexError: list index out of range

Does anyone have the solution?

4
  • Quick remark: name your variables by PEP8 standard like snake_case: en.wikipedia.org/wiki/Snake_case. Commented Dec 15, 2018 at 17:39
  • 3
    randint returns numbers including the second value, which results in an out-of-bounds access. Commented Dec 15, 2018 at 17:40
  • you need randrange then Commented Dec 15, 2018 at 17:45
  • 1
    len(characters) -1? Commented Dec 15, 2018 at 17:48

2 Answers 2

1

as explained in comments, you can get out of bounds for your string, unless you use random.randrange, which was added to avoid this issue (which can be stealthy because of the random aspect). More about this: Difference between random randint vs randrange

But a better solution would be random.choice to pick a random item from your string/list:

for x in range (0,24):
  RandChar = random.choice(characters)
Sign up to request clarification or add additional context in comments.

Comments

1

The randint function returns a value including both end points. If characters was 10 characters long, the highest number it could return is 10, which would be higher than the highest index, 9. You can change it to this:

for x in range (0,24):
    RandCharGen = random.randint(0,len(characters)-1) 
    RandChar = characters[RandCharGen]

or this:

for x in range (0,24):
    RandChar = random.choice(characters)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.