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?

Austin
  • 25,759
  • 4
  • 25
  • 48

2 Answers2

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)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
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)
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42