Python random choice
In this post, you will learn about the Python random() function.
There is an in-built random module in Python that's used to generate the pseudo-random variables. We can use this to perform some activity randomly, for example, to get a random number, choose an irregular element from a list, randomly shuffle elements, and so on. This module provides several functions to perform operations randomly. In this article, we will learn how to select an element randomly.
Python random.choice
The random.choice() method of the Python random module returns a random element from the given sequence.
Syntax of random.choice()
random.choice(sequence)
Here, the sequence can be any list, string, tuple, or any other kind of sequence. It returns a single item from the sequence. It is a required parameter. It will raise an error IndexError, in case we pass an empty list to the random.choice() function.
Example of random.choice()
Here, we have mentioned few examples of random.choice() method.
import random
x = "ETUTORIALSPOINT"
print("Random from x is: ",random.choice(x))
y = "LAPTOP"
print("Random item y is: ",random.choice(y))
Output of the above code-
Random from x is: T
Random item y is: O
Python random choice from list
In the given program, we are using a random random.choice() to select a random value from a list.
import random
num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random item from list is: ", random.choice(num_list))
Output of the above code-
Random item from list is: 234
Python multiple random choices from list
The choices() method of Python returns multiple random elements from the list with replacement. It was introduced in Python version 3.6. It has the following syntax-
random.choices(sequence, weights=None, *, cum_weights=None, k=1)
- sequence: The sequence can be a list, tuple, or string.
- weights: It is an optional parameter which is used to weigh the possibility of each value.
- cum_weights: It is an optional parameter which is used to weigh the possibility for each value, but in this the possibility is accumulated.
- k: It is an optional parameter that is used to define the length of the returned list.
In the given Python program, we are using the random.choices() function to select multiple random values from a list.
import random
num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random items from list: ", random.choices(num_list, k=3))
Output of the above code-
Random items from list: [121, 120, 121]
Python multiple random choices from list without repetition
In the above example, you have seen that we got a few repeated numbers as the choices() function can repeat elements. The random module of Python provides a sample() function for random sampling, randomly picking more than one element from the list without repeating elements. The following example demonstrates this.
from random import sample
num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random items from list: ", sample(num_list,3))
Output of the above code-
Random items from list: [121, 531, 232]
Python random choice from a set
A set is one of the built-in data types in Python used to store multiple items in a single variable. A set is created by using the built-in set() function, placing all the items inside the curly braces {}, separated by commas.
To select a random item from a set, first, copy it into a tuple and then pass the tuple to the choice() function.
import random
x_set = {60, 64, 23, 87, 39}
item = random.choice(tuple(x_set))
# random item from set
print("Random item from set: ", item)
Output of the above code-
Random item from set: 64
Python random choice from a tuple
A tuple is a sequence. Python tuples work exactly like a list, except tuples are immutable, which means they cannot be changed in place. The tuples are written inside parentheses. In the given program, we use the choice() method to select a random item from a tuple.
import random
tup = (25, 15, 63, 90)
# Random choice from a tuple
result = random.choice(tup)
print("Random item from tuple: ", result)
Output of the above code-
Random item from tuple: 63
Python random choice from a dictionary
Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of the character string. A dictionary is a collection, whose values are accessible by key. In the given program, we use the choice() function to select random key-value pairs from a Python dictionary. As, the choice() method doesn't directly work on dictionary, we need to convert a dictionary (dict) into a list and then pass it to the choice() method.
import random
x_dict ={
'Yellow': 'Marigold',
'Red': 'Rose',
'White': 'Lilly'}
# getting random key
x_list = random.choice(list(x_dict))
print("Random key-value pair- ", x_list, ":", x_dict[x_list])
Output of the above code:
Random key-value pair- White : Lilly
Related Articles
Sort dictionary by value Python
Add key value pair to dictionary Python
Python program to sum all the items in a dictionary
Convert dictionary to dataframe Python
Convert list to dictionary Python
range and xrange in Python
How to insert values in 2d array in python
splitlines in python
Make a simple calculator in Python
strip function in Python
casefold in Python
Prime factors of a number in Python
Python nonlocal keyword
Greatest common divisor Python recursive
Python String isalpha() Method
Program to print ASCII Value of a character
Python program to sort words in alphabetical order
*args and **kwargs in Python
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module