简体   繁体   中英

List index out of range error with Python 3

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?

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM