How To Pick A Random Word From A List In Python

To pick a random word from a List in Python, you can use the random.choice(), random.randint(), or random.choices() functions. Let’s see how to perform them with the explanation below.

Pick A Random Word From A List In Python

Using the random.choice() function

You can use the random.choice() function to pick a random word from a List in Python. After creating a list of words, you can apply the random.choice() function without hyperparameters to pick a word from it.

Look at the example below.

import random

# Create a list of words.
words = ['Learn', 'Share', 'IT', 'Python', 'Random', 'Word', 'Tutorial', 'Words']

# Pick a random word from a List with the random.choice() function 3 times.
print(random.choice(words))
print(random.choice(words))
print(random.choice(words))

Output

Share
Learn
IT

Using the random.randint() function

Besides the random.choice() function, you can pick a random word from a List in Python with the random.randint() function. In this case, you pick a position of the list with this function. Then, get the word from this position.

Look at the example below.

import random

# Create a list of words.
words = ['Learn', 'Share', 'IT', 'Python', 'Random', 'Word', 'Tutorial', 'Words']

# Pick a random word from a List with the random.randint() function 3 times.
print(words[random.randint(0, len(words) - 1)])
print(words[random.randint(0, len(words) - 1)])
print(words[random.randint(0, len(words) - 1)])

Output

Random
Learn
Random

Using the random.choices() function

In addition, you can use the random.choices() function to pick a random word from a List. It takes an argument name ‘k’ to random k values from a List. To pick a word, you assign k = 1. The result will be a list so you can get the desired result by getting the element at position 0.

Look at the example below.

import random

# Create a list of words.
words = ['Learn', 'Share', 'IT', 'Python', 'Random', 'Word', 'Tutorial', 'Words']

# Pick a random word from a List with the random.choices() function 3 times.
print(random.choices(words, k=1)[0])
print(random.choices(words, k=1)[0])
print(random.choices(words, k=1)[0])

Output

Learn
Python
Python

Besides, you can learn how to generate a random letter in Python here.

Summary

We have shared with you how to pick a random word from a List in Python. From our point of view, you should use the random.choices() function because it can pick multiple random values from a list, not only one. If you have any questions about this tutorial, leave your comment below and I will answer your question. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *