Random sampling from a list in Python
In this tutorial, we will learn about Random sampling from a list in Python.
We will use sample() function to return random values from a given list of elements. Random is a built-in Python module that returns random values. sample() is a submodule (function) of random module that helps to return a specific length of values.
Code to sample random values for a list
Let’s see an implementation of Sample function.
Import sample function from the Random module.
# Importing sample function from Random module from random import sample
Create a list of integers.
# Create a list containing integer values list_A = [20, 40, 60, 80, 100, 120, 140, 160]
# Print random elements from list of desired length print(sample(list_A,5))
Sample() function will take the given list and specific length of values to be returned, as parameters. Here 5 random values are returned from list_A.
Combining code
# Importing sample function from Random module from random import sample # Create a list containing integer values list_A = [20, 40, 60, 80, 100, 120, 140, 160] # Print random elements from list of desired length print(sample(list_A,5))
Output:
[120, 100, 160, 40, 60]
Output values will change every time you run the code.
Hence we have successfully generated Random sampling from a list of integers in Python.
Also, read:
Leave a Reply