How to Random sampling from a list in Python

Published on Aug. 22, 2023, 12:15 p.m.

sample

Here’s an updated example that uses the random.sample() method to randomly select a subset of elements from a Python list:

import random

my_list = [1, 2, 3, 4, 5]
sample = random.sample(my_list, 3)
print(sample)

In this example, we use the random.sample() method to select 3 random elements from the my_list list.

The random.sample() method takes two arguments: the first argument is the list from which you want to select elements, and the second argument is the number of elements you want to select. The method returns a new list containing the randomly-selected elements.

Note that the random.sample() method works only on sequences like lists, tuples or strings. If you want to randomly select elements from a numpy array or DataFrame, you can use the numpy.random.choice() method or the pandas.DataFrame.sample() method, respectively.

To randomly select an element from a Python array (or list)

To randomly select an element from a Python array (or list), you can use the random.choice() method from the random library. Here’s an example:

import random

my_array = [10, 20, 30, 40, 50]
random_element = random.choice(my_array)
print(random_element)

In this example, we use the random.choice() method to select a random element from the my_array list. The method takes a sequence as an argument and returns a randomly-selected element from that sequence.

Note that if you want to select multiple random elements from an array, you can use the random.sample() method (as I explained in my previous answer). But if you just want to select one random element, random.choice() is the way to go.

Another way to randomly select an element from a Python array

Another way to randomly select an element from a Python array is to use the random.randint() method with the len() function to generate a random index within the range of the array and then access the element at that index. Here’s an example:

import random

my_array = [10, 20, 30, 40, 50]
random_index = random.randint(0, len(my_array)-1)
random_element = my_array[random_index]
print(random_element)

In this example, we use the random.randint() method to generate a random index within the range of the my_array. We subtract 1 from the length of the array to make sure the index falls within the bounds of the array. We then use this random index to access the corresponding element in the array.

Note that this method works best for small arrays. If you’re working with a large array and only need to select one random element, using random.choice() may be more efficient.

Tags: