Register Login

How to Randomly Select Elements From a List in Python

Updated Nov 08, 2021

Selecting elements from a list has become a common operation performed by many programmers. It is mainly performed to carry out a randomized result from a list of recommendations or outcomes. Fetching values randomly from a collection of data is also popularly done in FPS games and adventure games. In this article, you will learn the different techniques of using random elements from the list.

Selecting Random elements from a List in Python

There are various approaches to fetch elements from a list randomly. Let us discuss each of them one by one.

Method 1: using randint():

The most intuitive and naive approach to solving this problem is to produce a random number that serves as the list index for accessing each element from the list randomly. Let us take a look at the technique of generating random numbers in Python using random.randint().

Program:

import random
letters = ['Ray', 'Karlos', 'Sue', 'Deeza', 'Bill', 'Steve']
random_index = random.randint(0, len(letters)-1)
print(letters[random_index])
random_index = random.randint(0, len(letters)-1)
print(letters[random_index])
random_index = random.randint(0, len(letters)-1)
print(letters[random_index])

Output:

1

3

Explanation:

Here, we have to import the random module first. Then, we have created a list full of string values. Then we have created a variable named random_index and assigned it with random.randint(0, len(letters)-1). The randint() will take two parameters and extract a single value from that list. Then we have repeated the same thing two more times to see the randomness of the function. You will see that the names are popping randomly from the list and getting displayed.

Method 2: Using randrange():

It is another method of the random module that returns a random number n such that n is greater than or equals 0 and less than a given number.

It uses the syntax:

random.randrange(start, stop, step)

Program:

import random
letters = [1, 2, 3, 4, 5, 6]
randm = random.randrange(len(letters))
print(letters[randm])
randm = random.randrange(len(letters))
print(letters[randm])
randm = random.randrange(len(letters))
print(letters[randm])

Output:

1
2
3

Explanation:

Here, we have to import the random module first. Then, we have created a list name “letters” full of integer values. Then we have created another variable name randm and generated a random number from the length of elements found within that list. Then we have repeated the same thing two more times to see the randomness of the function. You will see that the numbers are popping randomly from the list and getting displayed.

Method 3: using random.sample():

This method helps in returning a random list that requires a list of items from a given sequence. This method does not recognize duplicate elements within the list. Therefore, if you want to pick elements from the list randomly by eliminating the duplicate elements, this method is the best. You have to simply pass 2 parameters – the first parameter holds the sequence or the compound data type while the second is the number of random elements you want from that sequence (here list).

Program:

import random
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numb = 5
print(random.sample(li, numb))

Output:

[5, 1, 6, 8, 4]

Explanation:

Here, we have to import the random module first. Then, we have created a list name “li” full of integer values from 1 up to 9. Then we have created another variable “numb” and mentioned the number of times we want to generate random numbers from the list. Then, finally we have printed the random.sample() value and passed the list from where this function will fetch the random values as well as the variable numb that is designating the number of random elements to be generated and displayed.

Method 4: Using random.choice() method:

This method helps in returning the random number from a given sequence (here list). It picks the available value from a set of elements and considers duplicate values also. Since it takes duplicate value into consideration, you can use it in situations where you can bring in duplicate values such the same timing in games.

Program:

import random
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
numb = 5
for i in range(numb):
print(random.choice(li), end =" ")

Explanation:

Here, we have to import the random module first. Then, we have created a list name “li” full of integer numbers from 1 up to 9. Then we have created another variable “numb” and mentioned the number of times we want to generate random numbers from the list. Then, we have created a ‘for’ loop that will iterate till the initialized value of numb. Within the body of the for(), we have printed the random.choice() and passed the list that will generate random value with a space following it.

Method 5: Using shuffle() within the user-defined function:

As the name suggests, it shuffles the elements of the list & partitions it into n different parts. It guarantees that no duplicate elements get added because it just slices the list and shuffles it making the collections random.

Program:

import random
def choose_rand(li, numb):
    random.shuffle(li)
    res = []
    for elem in range(0, len(li), numb):
        res.append(lst[elem: elem + numb])
    return res
        
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
print(choose_rand(lst, 2))

Output:

[['e', 'c'], ['a', 'h'], ['d', 'f'], ['g', 'b']]

Explanation:

Here, we have to import the random module first. Then, we have define a choice_rand() user-defined function that is having two parameters (li and numb). Within that function body, we have called the random.shuffle() function and passed the li (list). Then we have created another empty list “res”. Within that function, we have created a for loop that will iterate from 0 till the length of li list with a step of numb-value.

Finally, within that function, we have res.append() that will append the elements into the list and return the res value. Outside the function body, we have created a list and assigned it with a set of characters. Lastly, we have to print the returned value of the function using the print().

Conclusion:

All of these techniques are useful and all of them have almost the same programming efficiencies. Now, programmers have to check which program is taking lesser variable or lesser loops to perform the execution. So, programmers can use anyone they want based on their preferred choices.


×