Search code examples
pythonpython-3.xrandom

How do I choose a random string from a Python list?


I am trying to get a random string from a Python list. Is there any built-in function to do that? I often use random.randint() like this:

import random
word_stack=['A','B','C','D']

print(word_stack[random.randint(len(word_stack))])

but that's slow, due to a large number of words. (I'm building a word guess challenge.)


Solution

  • Take a look at random.choice which does exactly what you need. For your case, it would look like this:

    word_stack = ['A','B','C','D']
    random_str = random.choice(word_stack)
    print(random_str)  # -> whatever
    

    Having said that, I wouldn't expect it to make such a big difference on the speed of the process. But If I find the time I will test it.