How do i choose random string from python list other than using random.randint() in index?

1.9k Views Asked by At

I am trying to retrieve a random string from python list to build a word guess challenge. I deployed anaconda environment on Alibaba Cloud ECS Instance.

I often use the following method to retrieve a random string from the list.

Let's say

WordStack=['A','B','C','D']
print(WordStack[random.randint(len(WordStack))])

Is there any optimized way or build-in funtion to do that? Due to a large number of words, it takes some time to give the result.

2

There are 2 best solutions below

0
On BEST ANSWER

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

WordStack = ['A','B','C','D']
random_str = random.choice(WordStack)
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.

0
On

You could try random.randrange() instead of random.randint().

random.randrange():

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

From https://docs.python.org/3/library/random.html#random.randrange

I am not aware of any built-in function that does this.

So the equivalent statement would be:

WordStack[random.randrange(len(WordStack))]