简体   繁体   中英

I am trying to print a random index of the list using random.randint, but Im getting list index out of range

I'm newbie in programming learning Python. I'm getting started with list. In the following program I am trying to print a random index of the list using random.randint, but Im getting list index out of range. The random number is given a range which is within the length of the List.

import random

members = ["Al, Am, Da, Ma, Sa, Za"]
print("The winner is: " + members[random.randint(0,5)])

Your entire list is just one string. You need to have each element separated by commas to indicate that they're each their own elements.

members = ["Al", "Am", "Da", "Ma", "Sa", "Za"]

Welcome to Stackoverflow. First of all, your list is one string, and you need to separate each string with commas. After you've done that, your code will work fine. An easier way of choosing a random item in the list is with random.choice(method) which chooses a random element in the data structure you provide. Your finalized code looks like this:

 import random members = ["Al", "Am", "Da", "Ma", "Sa", "Za"] print("The winner is: " + random.choice(members))

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