Random word from list 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.

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!

My name is Thomas Valen. As a software developer, I am well-versed in programming languages. Don’t worry if you’re having trouble with the C, C++, Java, Python, JavaScript, or R programming languages. I’m here to assist you!

Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Java, Python, JavaScript, R

Home » Python » Random » Python random choice() function to select a random item from a List and Set

In this lesson, You will learn how to use Python’s random.choice() function to select a random item from a list and other sequence types. You will also learn how to pick a random item from multiple lists.

Use the following functions of a random module to generate a random choice from a sequence. We will see each one of them with examples.

Function Description
random.choice(list) Choose a random item from a sequence. Here seq can be a list, tuple, string, or any iterable like range.
random.choices(list, k=3) Choose multiple random items from a list, set, or any data structure.
random.choice(range(10, 101)) Pick a single random number from range 1 to 100
random.getrandbits(1) Returns a random boolean
random.choice(list(dict1)) Choose a random key from a dictioanry
np.random.choice() Return random choice from a multidimensional array
secrets.choice(list1) Choose a random item from the list securely
functions to generate random choice

Table of contents

  • Python random.choice() function
    • Examples
  • Select a random item from a list
  • Select multiple random choices from a list
  • Random choices without repetition
  • Random choice from a Python set
  • Random choice within a range of integers
  • Get a random boolean in using random.choice()
  • Random choice from a tuple
  • Random choice from dictionary
  • Randomly choose an item from a list along with its index position
  • Pick a random value from multiple lists with equal probability
  • Choose a random element from a multidimensional array
    • A random choice from a 2d array
    • Random choice from 1-D array
  • Secure random choice
  • Randomly choose the same element from the list every time
  • Randomly choose an object from the List of Custom Class Objects
  • Next Steps

The choice() function of a random module returns a random element from the non-empty sequence. For example, we can use it to select a random password from a list of words.

Syntax of random.choice()

random.choice(sequence)

Here sequence can be a list, string, or tuple.

Return Value:

It returns a single item from the sequence. If you pass an empty list or sequence to choice() It will raise IndexError (Cannot choose from an empty sequence).

Examples

Now let see how to use random.choice() with the example program.

import random

number_list = [111, 222, 333, 444, 555]
# random item from list
print(random.choice(number_list))
# Output 222

Select a random item from a list

Let assume you have the following list of movies and you want to pick one movie from it randomly

movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']

In this example, we are using a random random.choice() to select an item from the above list randomly.

import random

movies_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']

# pick a random choice from a list of strings.
movie = random.choice(movies_list)
print(movie)
# Output 'The Shawshank Redemption'

for i in range(2):
    movie = random.choice(movies_list)
    print(movie)
# Output 
# 'Citizen Kane'
# 'The Shawshank Redemption'

As you can see, we executed the random.choice() function two times, and every time we got a different item from a list. Also, there are other ways to select a random item from a list. Let’s see those now.

Select multiple random choices from a list

The choice() function only returns a single item from a list. If you want to select more than one item from a list or set, use random sample() or choices() instead.

random.choices(population, weights=None, *, cum_weights=None, k=1)
  • The random.choices() method was introduced in Python version 3.6, and it can repeat the elements. It is a random sample with a replacement.
  • Using the random.choices(k) method we can specify the sampling size.

Example: Pick three random items from a list

import random

# sampling with replacement
original_list = [20, 30, 40, 50, 60, 70, 80]
# k = number of items to select
sample_list = random.choices(original_list, k=3)
print(sample_list)
# Output [60, 20, 60]

As you can see in the above example, we used the random.choices() and passed three as a sampling size (the total number of items to select randomly)

As you can see in the output, we got a few repeated numbers because the choices() function can repeat elements.

Random choices without repetition

Use the random.sample() function when you want to choose multiple random items from a list without repetition or duplicates.

There is a difference between choice() and choices().

  • The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.
  • The choices() function is mainly used to implement weighted random choices to choose multiple elements from the list with different probabilities.

Also, don’t forget to solve our Python random data generation exercise.

Random choice from a Python set

Python Set is an unordered collection of items. If we pass the set object directly to the choice function, we will get the TypeError ('set' object does not support indexing).

So we can’t choose random items directly from a set without copying them into a tuple.

To choose a random item from a set, first, copy it into a tuple and then pass the tuple to the choice() function

import random

sample_set = {20, 35, 45, 65, 82}
item = random.choice(tuple(sample_set))
# random item from set
print(item)
# Output 65

Random choice within a range of integers

Python range() generates the integer numbers between the given start integer to the stop integer. In this example, we will see how to use the choice() to pick a single random number from a range of integers.

Example:

import random

# Choose randomly number from range of 10 to 100
num = random.choice(range(10, 101))
print(num)
# Output 93

Get a random boolean in using random.choice()

In Python, boolean values are either True or False. Such as flip a coin to select either coin head and tail randomly. Let’s see how to choose a random boolean value, either True or False

Example:

import random

res = random.choice([True, False])
print(res)
# Output True

Also, you can use the random.getrandbits() to generate random Boolean in Python fastly and efficiently.

Example:

import random

# get random boolean
res = random.getrandbits(1)
print(bool(res))
# Output False

Random choice from a tuple

Same as the list, we can choose a random item out of a tuple using the random.choice().

import random

atuple = (20, 30, 4)
# Random choice from a tuple
num = random.choice(atuple)
print(num)
# Output 30

Random choice from dictionary

Dictionary is an unordered collection of unique values stored in (Key-Value) pairs. Let see how to use the choice() function to select random key-value pair from a Python dictionary.

Note: The choice() function of a random module doesn’t accept a dictionary. We need to convert a dictionary (dict) into a list before passing it to the choice() function.

import random

weight_dict = {
    "Kelly": 50,
    "Red": 68,
    "Scott": 70,
    "Emma": 40
}
# random key
key = random.choice(list(weight_dict))
# fetch value using key name
print("Random key-value pair is ", key, ":", weight_dict[key])
# Output Random key-value pair is  Red : 68

Randomly choose an item from a list along with its index position

Many times we need an index position of an item along with its value. You can accomplish this using a randrange() function. So let see how to randomly choose an item from a list along with its index position.

from random import randrange

movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']

# get random index number
i = randrange(len(movie_list))
item = movie_list[i]
# Select item using index number
print("Randomly selected item", movie_list[i], "is present at index:", i)

# Output Randomly selected item Citizen Kane is present at index: 2

Pick a random value from multiple lists with equal probability

Equal probability means each item from all lists has a fair chance of being selected randomly.

After the introduction of choices() in Python 3.6, it is now easy to generate random choices from multiple lists without needing to concatenate them. Let’s see how to choose items randomly from two lists.

See: Weighted random choice from more detail.

import random

list_one = ["Thomas", "Liam", "William"]
list_two = ["Emma", "Olivia", "Isabella"]

seqs = list_one, list_two

# Random item  from two lists
item = random.choice(random.choices(seqs, weights=map(len, seqs))[0])
print(item)
# Output William

Choose a random element from a multidimensional array

Most of the time, we work with 2d or 3d arrays in Python.

  • Use the numpy.random.choice() function to generate the random choices and samples from a NumPy multidimensional array.
  • Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.

A random choice from a 2d array

import numpy as np

array = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])
print("Printing 2D Array")
print(array)

print("Choose random row from a 2D array")
randomRow = np.random.randint(3, size=1)
print(array[randomRow[0], :])

print("Random item from random row is")
print(np.random.choice(array[randomRow[0], :]))

Output:

Printing 2D Array
[[11 22 33]
 [44 55 66]
 [77 88 99]]

Choose random row from a 2D array
[44 55 66]

Random number from random row is
66

Random choice from 1-D array

import numpy as np

array = [10, 20, 30, 40, 50, 20, 40]

x = np.random.choice(array, size=1)
print("single random choice from 1-D array", x)

items = np.random.choice(array, size=3, replace=False)
print("multiple random choice from numpy 1-D array without replacement ", items)

choices = np.random.choice(array, size=3, replace=True)
print("multiple random choices from numpy 1-D array with replacement ", choices)

Output

single random choice from 1-D array [40]

multiple random choice from numpy 1-D array without replacement  [10 20 40]

multiple random choices from numpy 1-D array with replacement  [20 30 20]

Secure random choice

Note: Above all, examples are not cryptographically secure. If you are using it to pick a random item inside any security-sensitive application, then secure your random generator and use random.SystemRandom().choice() instead of random.choice().

import random

movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
# secure random generator
secure_random = random.SystemRandom()
item = secure_random.choice(movie_list)
print (item)
# Output 'The Godfather'

Randomly choose the same element from the list every time

Choosing the same element out of a list is possible. We need to use the random.seed() and random.choice() function to produce the same item every time. Let see this with an example.

import random

float_list = [22.5, 45.5, 88.5, 92.5, 55.4]
for i in range(5):
    # seed the random number generator
    random.seed(4)
    # print random item
    print(random.choice(float_list))

Output:

45.5
45.5
45.5
45.5
45.5

To get the same choice from the list randomly, you need to find the exact seed root number.

Randomly choose an object from the List of Custom Class Objects

For example, you have a list of objects, and you want to select a single object from the list. Here, a list of objects is nothing but a list of user-defined class objects. Let’ see how to choose a random object from the List of Custom class objects.

import random

# custom class
class studentData:
    def __init__(self, name, age):
        self.name = name
        self.age = age


jhon = studentData("John", 18)
emma = studentData("Emma", 19)

object_list = [jhon, emma]

# pick list index randomly using randint()
i = random.randint(0, len(object_list) - 1)
# Randomly select object from the given list of custom class objects
obj = object_list[i]
print(obj.name, obj.age)
# Output John 18

Next Steps

I want to hear from you. What do you think of this article? Or maybe I missed one of the usages of random.choice(). Either way, let me know by leaving a comment below.

Also, try to solve the following Free exercise and quiz to have a better understanding of working with random data in Python.

  • Python random data generation Exercise to practice and master the random data generation techniques in Python.
  • Python random data generation Quiz to test your random data generation concepts.

Reference : Python documentation on random choice.

This is a useful program that chooses a random word from a given list.

Run:

python Random_word_from_list.py
Code language: CSS (css)

Make sure you have a file in the same directory you wish to choose a random word from.

Random_word_from_list.py

import sys
import random

# check if filename is supplied as a command line argument
if sys.argv[1:]:
    filename = sys.argv[1]
else:
    filename = input("What is the name of the file? (extension included): ")

try:
    file = open(filename)
except (FileNotFoundError, IOError):
    print("File doesn't exist!")
    exit()
# handle exception

# get number of lines
num_lines = sum(1 for line in file if line.rstrip())

# generate a random number between possible interval
random_line = random.randint(0, num_lines)

# re-iterate from first line
file.seek(0)

for i, line in enumerate(file):
    if i == random_line:
        print(line.rstrip())  # rstrip removes any trailing newlines :)
        breakCode language: PHP (php)


This post goes over how to generate a random word or letter in Python.

Install

Install random-word and PyYaml:

pip3 install random-word pyyaml

PyYaml is required or else you’ll get the error:

ModuleNotFoundError: No module named 'yaml'

Usage

Generate a random word:

from random_word import RandomWords

random_words = RandomWords()
print(random_words.get_random_word())

See the package documentation for more information.

Demo

Replit:

Random Letter

Get a random letter from the alphabet:

from string import ascii_lowercase
from random import randrange

print(ascii_lowercase[randrange(len(ascii_lowercase))])

Demo

Replit:



Please support this site and join our Discord!


Given a list and our task is to randomly select elements from the list in Python using various functions. Selecting random numbers from a list can be used sometimes while building games, choosing a random range, etc. 

Example :

Input: [2, 3, 4 , 5, 6 ]
Output: 2
Input: [3, 5, 6, 3, 2]
Output: 6

Using random.choice()  to select random value from a list

This random.choice() function is designed for getting a Random sampling from a list in Python and hence is the most common method to achieve this task of fetching a random number from a list. 

Python3

import random

test_list = [1, 4, 5, 2, 7]

print("Original list is : " + str(test_list))

random_num = random.choice(test_list)

print("Random selected number is : " + str(random_num))

Output:

Original list is : [1, 4, 5, 2, 7]
Random selected number is : 1

Using random.randrange() to select random value from a list

random.randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.

Python3

import random

test_list = [1, 4, 5, 2, 7]

print("Original list is : " + str(test_list))

rand_idx = random.randrange(len(test_list))

random_num = test_list[rand_idx]

print("Random selected number is : " + str(random_num))

Output:

Original list is : [1, 4, 5, 2, 7]
Random selected number is : 7

Using random.randint() to select random value from a list

random.randint() is used to generate the random number, also this can be used to generate any number in a range, and then using that number, we can find the value at the corresponding index, just like the above-mentioned technique. But it differs by the fact that it requires 2 mandatory arguments for range. 

Python3

import random

test_list = [1, 4, 5, 2, 7]

print("Original list is : " + str(test_list))

rand_idx = random.randint(0, len(test_list)-1)

random_num = test_list[rand_idx]

print("Random selected number is : " + str(random_num))

Output:

Original list is : [1, 4, 5, 2, 7]
Random selected number is : 4

Using random.random() to select random value from a list

random.random() method generates the floating-point numbers in the range of 0 to 1. We can also get the index value of list using this function by multiplying the result and then typecasting it to integer so as to get the integer index and then the corresponding list value. 

Python3

import random

test_list = [1, 4, 5, 2, 7]

print("Original list is : " + str(test_list))

rand_idx = int(random.random() * len(test_list))

random_num = test_list[rand_idx]

print("Random selected number is : " + str(random_num))

Output:

Original list is : [1, 4, 5, 2, 7]
Random selected number is : 7

Using random.sample() to select random value from a list

Python has a built-in function called random.sample(). The random module contains the random.sample() function. It has the ability to choose multiple items from a list.

Python3

import random

test_list = [1, 4, 5, 2, 7]

print("Original list is : " + str(test_list))

print("Random element is :", random.sample(test_list, 5))

Output:

Original list is : [1, 4, 5, 2, 7]
Random element is : [7, 4, 1, 5, 2]

Using random.choices() to select random value from a list

The random.choices function is stored in the random module (). Selecting numerous items from a list or a single item from a particular sequence is handy with the help of random.choices function.

Python3

import random

test_list = [11, 44, 55, 22, 77]

print("Original list is : " + str(test_list))

print("Random element is :", random.choices(test_list, k=4))

Output:

Original list is : [11, 44, 55, 22, 77]
Random element is : [11, 11, 44, 77]

Select k random value from a list

Here we have grouped all elements in a pair of size k.

Python3

import random

def select_random_Ns(l, k):

    random.shuffle(l)

    res = []

    for i in range(0, len(l), k):

        res.append(l[i:i + k])

    return res

l = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

print(select_random_Ns(l, 3))

Output:

[['G', 'G', 'R'], ['K', 'K', 'E'], ['O', 'F', 'E'], ['S', 'E', 'S'], ['E']]

Using numpy.random.choice() to select random value from a list

Note: Install numpy using “pip install numpy”

The numpy.random.choice() method is used for getting a random sample from an array in numpy. It is also possible to generate a random sample from a list by converting the list to a numpy array.

Algorithm:

Import numpy and initialize the list.
Convert the list to a numpy array.
Use numpy.random.choice() method to select a random value from the array.
Print the selected value.

Python3

import numpy as np

test_list = [2, 3, 4, 5, 6]

test_array = np.array(test_list)

random_num = np.random.choice(test_array)

print("Random selected number is : " + str(random_num))

Output:

Random selected number is : 5

Time Complexity:
The time complexity of the numpy.random.choice() method is O(k), where k is the size of the sample to be generated.

Space Complexity:
The space complexity of the numpy.random.choice() method is O(n), where n is the size of the array.

Понравилась статья? Поделить с друзьями:
  • Random word and definition
  • Random values in excel
  • Random spaces in word
  • Random one word names
  • Random it words and word