You are currently viewing Python random.choice() Function

The random.choice() is a method in the random modupyspark joins
le in Python. It generates a single random element from a specified sequence such as a list, a tuple, a range, a string, etc. This is one of the most useful functions to generate random numbers from the sequence. It takes a sequence as its parameter and returns a single random element from the sequence.

Advertisements

In this article, I will explain random.choice() function syntax, parameter, and usage of how we can return the single random element from a given sequence.

1. Quick Examples of random.choice() Function

If you are in a hurry, below are some quick examples of random.choice() function.


# Quick examples of random.choice() function

# Example 1: Get random element using random.choice()
rand_num = random.choice(range(10))
 
# Example 2: Get the random character
str = 'Python'
for _ in range(2):
    rand_num = random.choice(str)

# Example 3: Get the random string using choice()
# Initialize the list
list = ["Python", "Pandas", "Spark", "PySpark"]
rand_num = random.choice(list)

# Example 4: # Get a random key/value from the dictionary.
# Create a dictionary
dict = {
    "course": "Python" ,
    "Fee": 4500,
    "duration": '45 days'
}
key = random.choice(list(dict))

# Example 5: # Get a random element from the tuple.
# Create a tuple
tuple =  ('Python', 'Pandas', 'Spark', 'PySpark')
rand_num = random.choice(tuple)

# Example 6: Get multiple random elements
# Initialize string
str = 'Python'
rand_num = random.choices(str, k =2)

2. Python random.choice() Function

The random.choice() is a part of random module of Python that returns a single random element from a sequence. It takes sequence as its parameter and generates a single random element from it.

  • Note1: When we pass a number instead of a sequence, it will raise TypeError.
  • Note2: When we pass an empty sequence into this function, it will raise a IndexError.

2.1 Syntax of random.choice()

Following is the syntax of the random.choice().


# Syntax of  random.choice()
random.choice(sequence)

2.2 Parameters of random.choice()

It takes only one parameter.

2.3 Return Value

It returns a single random element from a specified sequence such as a list, a tuple, a range, a string, etc. If the sequence is empty, it will raise an IndexError.

3. Using random.choice() to Select Random Number

You can use Python random.choice() function to generate a single random element from a sequence like list, set e.t.c. Alternatively, you can also use the range() function that takes the start and end points and generates the sequence of numbers between them.

Let’s take a range(10) sequence and pass it into the choice() function to get the single random element from the sequence. The random value returns are different for every execution, some times you may also get the same value. Before going to use this function we need to import a random module.


# Get random element using random.choice()
# Import random module
import random
rand_num = random.choice(range(10))
print("Random element:", rand_num )

Yields below output.

Python random choice

4. Get Random character using Pyhton random.choice()

Create a string and pass it into the choice() function, it will get a single character randomly. Let’s check how it generates a random character for every execution using for loop.


# Import random module
import random

# Initialize the string
# Get the random character
str = 'Python'
for _ in range(2):
    rand_num = random.choice(str)
    print("Random element:", rand_num)

Yields below output.

Python random choice

You can notice from the above, that a random character has been generated differently from the given string two times.

5. Get Random String using Pyhton random.choice()

You can use random.choice() upon the list of stings to get a single random string from the given list. Let’s initialize the list with strings and pass it into the choice() function to get the single string from a list of strings randomly.


import random

# Initialize the list
list = ["Python", "Pandas", "Spark", "PySpark"]
print("List:", list)

# Get the random string using choice()
rand_num = random.choice(list)
print("Random Element:", rand_num)

# Output:
# List: ['Python', 'Pandas', 'Spark', 'PySpark']
# Random Element: PySpark

6. Get Random Key/Value Pair using Python choice()

You can use random.choice() upon the dictionary to get a single random key/value pair from the given dictionary. First initialize the dictionary and get the dictionary keys as list and pass it as an argument to choice(). Finally, we can get the random key from the dictionary, and now use the this key to access the corresponding value.


# Create a dictionary
dict = {
    "course": "Python" ,
    "Fee": 4500,
    "duration": '45 days'
}
print("Dictionary:", dict)

# Get a random key from the dictionary.
key = random.choice(list(dict))

# Print the key-value using the key name.
print("Random key/value pair:", key ,":", dict[key])

# Output: 
# Dictionary: {'course': 'Python', 'Fee': 4500, 'duration': '45 days'}
# Random key/value pair: duration : 45 days

7. Pass Tuple into Random choice() in Python

You can use random.choice() upon the tuple of strings to get a single random string from the given tuple. Let’s initialize the tuple with strings and pass it into the choice() function to get the single string from a tuple of strings randomly.


# Create a tuple
tuple =  ('Python', 'Pandas', 'Spark', 'PySpark')
print("Tuple:", tuple)

# Get a random element from the tuple.
rand_num = random.choice(tuple)
print("Random element:", rand_num)

# Output:
# Tuple: ('Python', 'Pandas', 'Spark', 'PySpark')
# Random element: Spark

8. Exception

When we pass an empty sequence into the choice() function, it will raise an IndexError. Let’s create an empty list and pass it into a method that will get you an IndexError. You can use try excep to handle the exception.


import random

# Create a empty list
# Pass empty_list into choice()
empty_list =  []
rand_num = random.choice(empty_list)
print("Random element:", rand_num)

# Output:
# IndexError: list index out of range

When we pass a number instead of a sequence, it also raises TypeError. Let’s see,


import random
# Pass integer into choice() 
# Create a dictionary
integer = 50
rand_num = random.choice(integer)
print("Random element:", rand_num)

# Output:
# TypeError: object of type 'int' has no len()

9. Generate Multiple Elements from Sequence

So, far we have learned how to get a single random element from a sequence using python random.choice(). Now we will learn how to get multiple random numbers from a sequence. You can use the random.choices() function that generates multiple random elements from a given sequence.

So to generate a list of random characters using random.choices(), use the function with the parameter string and k=2 to specify that we want to generate two random characters.


import random

# Initialize string
str = 'Python'
print("String:", str)
rand_num = random.choices(str, k =2)
print("Random list:", rand_num )

# Output:
# String: Python
# Random list: ['t', 'n']

10. Conclusion

In this article, I have explained Python random.choice() function syntax, parameters, and usage of how to get a single random element from a given sequence. And also explained using choices() function to get the multiple random elements from given sequence.

Happy Learning!!

Related Article