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 |

## Table of contents

- Python random.choice() function
- 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
- 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

## Python `random.choice()`

function

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.choice`

method was introduced in Python version 3.6, and it can repeat the elements. It is a random sample with a replacement.**s**() - Using the
`random.choice`

method we can specify the sampling size.**s**(k)

**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.