In this article, I will let you know how to **select a random item from a list and other sequence types** in Python. Python random module has a function `choice()`

to randomly choose an item from a list and other sequence types.

**Goals of this lesson. **In this lesson, you’ll learn how to:

- Randomly select an item from a list, set, tuple, and dictionary
- Randomly select multiple choices from the list
- Pick a random number from a range
- Get a random boolean in Python
- Pick a random value from multiple lists
- Choose a random element from a multidimensional array
- Choose the same element from the list every time

**Further reading**

## Python random.choice() function

Python random module‘s `random.choice()`

function returns a random element from the non-empty sequence. we can use the `random.choice()`

function for selecting a random password from word-list, Selecting a random item from the available data.

**Syntax of random.choice()**

`random.choice(sequence)`

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

**Return Value**: -This function **returns a single item from the sequence**. If we pass an empty list or sequence to `random.choice()`

function it will raise **IndexError: **Cannot choose from an empty sequence.

### random.choice() Examples

Now let see how to use `random.choice()`

with the example program.

```
import random
numberList = [111,222,333,444,555]
print("random item from list is: ", random.choice(numberList))
```

**Output**:

Random item from list is: 333

## Use random.choice() to Randomly select an item from a list

Let assume you have the following movies list and you want to pick one movie from it randomly. Now, Let’s see the example to pick a random choice from a list of strings.

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

In this example, we are using a `random.choice()`

to select an item from the above list randomly.

```
import random
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
moview_item = random.choice(movie_list)
print ("Randomly selected item from list is - ", moview_item)
moview_item = random.choice(movie_list)
print ("Randomly selected item from list is - ", moview_item)
```

**Output**:

Randomly selected item from a list using random.choice is - The Shawshank Redemption Randomly selected item from a list using random.choice is - The Godfather

As you can see we executed `random.choice()`

function two times and every time we got a different item from a list. Also, there are other ways to randomly select an item from a list lets see those now.

## Randomly select multiple choices from the list

As you know, the `random.choice ()`

function only returns a single item from a list. If you want to randomly select more than one item from a list or set, I’d recommend using random.sample() or random.choice**s**() instead.

**Example**:

```
import random
#sampling with replacement
list = [20, 30, 40, 50 ,60, 70, 80]
sampling = random.choices(list, k=4)
print("Randomly selected multiple choices using random.choices() ", sampling)
```

**Output**:

Randomly selected multiple choices using random.choices() [80, 50, 40, 60, 40]

As you can see in the above example we used `random.choices()`

and passed the sampling size i.e., the total number of items that we want to choose from the list randomly.

Also, as you can see in the output, we got a few repeated numbers. `random.choices()`

can repeat elements.

### Python random choices without repetition

The `random.sample()`

- Use the
`random.sample()`

function when you want to*choose multiple random items from a list*.**without repetition or duplicates** - Please read our detailed tutorial on random.sample().

**Important Note**:

There is a difference between `random.choice()`

and `random.choice`

.**s**()

The `random.choices()`

- Python
`random.choices()`

was added in Python 3.6 to choose`n`

elements from the list randomly, but this function**can repeat elements**. - The
`random.choices()`

is mainly used to implement**weighted random choices**so that we can choose elements from the list with different probabilities.

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

## The random choice from a set in Python

If we pass Set object directly to the choice function we will get the TypeError: ‘set’ object does not support indexing.

Using the `random.choice`

function **we can’t choose random items directly from a set, without having to copy it into a tuple**. Let see how to use a choice function to select a random item from Set.

```
import random
weight_set = {20, 35, 45, 65, 82}
weight = random.choice(tuple(weight_set))
print ("Randomly item from Set is - ", weight)
```

**Output**:

Randomly item from Set is - 65

## Python random choice within a range of integers

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

Example:

```
import random
print("randomly choose any number between the range of 10 to 100")
num = random.choice(range(10, 101))
print(num)
```

Output:

randomly choose any number between the range of 10 to 100 54

## Get a random boolean in Python using random.choice()

For example, we need to choose random boolean value when we want to choose True or False randomly such as flip a coin.

**Example**:

```
import random
res = random.choice([True, False])
print("Random boolean is")
print(res)
```

Output:

Random boolean is True

#### Faster and Efficient way to generate random boolean in Python

We need to use `random.getrandbits()`

Example:

```
import random
print("Random boolean is")
res = random.getrandbits(1)
print(bool(res))
```

Output:

Random boolean is False

## Python random choice from a tuple

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

. Let see this with an example program.

```
import random
atuple = (20, 30, 4)
print("Random choice from a tuple")
num = random.choice(atuple)
print(num)
```

Output:

Random choice from a tuple 30

## The random choice from Python Dictionary

Let see how to use the `random.choice()`

function to select random **key-value pair** from a Python dictionary. The random.choice() function of a random module doesn’t accept a dictionary, you need to convert a dictionary into a list before passing it to `randonm.choice()`

function. Let see the example of how to choose `dict`

keys randomly.

```
import random
weight_dict = {
"Kelly": 50,
"Red": 68,
"Jhon": 70,
"Emma" :40
}
key = random.choice(list(weight_dict))
print ("Random key-value pair from dictonary is ", key, " - ", weight_dict[key])
```

**Output**:

Random key value pair from dictonary is Jhon - 70

## Randomly choose the same element from the list every time

Choosing the same element out of a list is possible. We need to use random.seed() and `random.choice`

function together to produce the same element every time. Let see this with an example.

```
import random
float_list = [22.5, 45.5, 88.5, 92.5, 55.4]
random.seed(4)
random_item = random.choice(float_list)
print("random item", random_item)
random.seed(4)
random_item = random.choice(float_list)
print("random item", random_item)
```

**Output**:

random item 45.5 random item 45.5

This is just a simple example. To get the same choice from the list randomly every time, you need to find the exact seed root number.

Refer to this article on Python random.seed(): how to find the seed root.

## 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 random.randrange() function. So let see how to randomly choose an item from a list along with its index position.

**Example**: –

```
from random import randrange
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
random_index = randrange(len(movie_list))
item = movie_list[random_index]
print ("Randomly selected item and its index is - ", item, "Index - ", random_index)
```

**Output**:

Randomly selected item from list using randrange- The Wizard of Oz Inex - 1

## Choose a random element from a multidimensional array in Python

Most of the time we work with 2-d or 3-d arrays in Python. Let assume you want to pick a random element from it then how to do it? Let see this with an example. In this example, We used `numpy.random.choice()`

function to pick a random element from the multidimensional array.

**A random choice from 2d array**

```
import numpy
array = numpy.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 = numpy.random.randint(3, size=1)
print(array[randomRow[0],:])
print("Random number from random row is")
print(numpy.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

**Note**: Above all, examples are not cryptographically secure. If you are doing this for any security-sensitive application then to cryptographically secure random output, use `random.SystemRandom().choice`

instead of `random.choice()`

.

Read more on how to generate random data in Python securely.

Now, Let see how to generate a cryptographically secure random choice.

```
import random
movie_list = ['The Godfather', 'The Wizard of Oz', 'Citizen Kane', 'The Shawshank Redemption', 'Pulp Fiction']
secure_random = random.SystemRandom()
item = secure_random.choice(movie_list)
print ("cryptographically secure random choice - ", item)
```

**Output**:

cryptographically secure random choice - The Godfather

## Pick a random value from multiple lists with equal probability

When we say equal probability, it means that each item from all lists will have a fair chance of being selected randomly. After the introduction of r`andom.choices()`

in Python 3.6, it is now easy to generate random choice from multiple lists without needing to concatenate them.

Let’s see how to choose value randomly from two lists using `random.choice()`

and `random.choices()`

.

```
import random
list_one = ["Thomas", "Liam", "William"]
list_two = ["Emma", "Olivia", "Isabella"]
seqs = list_one, list_two
print("Random choice from two lists")
val = random.choice(random.choices(seqs, weights=map(len, seqs))[0])
print(val)
```

Output:

Random choice from two lists William

## Python Randomly choose an object from the List of Class Objects

For example, you have a list of objects (class instance) and you want to select a single object from the list. Let’s see how to choose a single object from the given list of custom Class objects.

```
import random
class studentData:
def __init__(self, name, age):
self.name = name
self.age = age
jhon = studentData("John", 18)
emma = studentData("Emma", 19)
objectList = [jhon, emma]
# pick list index randomly using randint()
objectIndex = random.randint(0, len(objectList)-1)
randomObject = objectList[objectIndex]
print("Randomly selected object from the given list of custom class objects is")
print(randomObject.name, randomObject.age)
```

**Output**:

Randomly selected object from the given list of custom class objects is John 18

## So What Do You Think?

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.