get a sample of 5 elements from an array without replacement in python

To get a sample of 5 elements from an array without replacement in Python, you can use the random.sample() function from the random module. The random.sample() function returns a new list containing unique elements chosen randomly from the input sequence.

Here's an example code snippet that demonstrates how to use random.sample() to get a sample of 5 elements from an array without replacement:

main.py
import random

# Create an example array of numbers
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use random.sample() to get a sample of 5 elements without replacement
sample = random.sample(arr, k=5)

print(sample)
211 chars
10 lines

In this code, we first import the random module. Then, we define an example array arr containing 10 numbers. Finally, we use the random.sample() function to get a sample of 5 elements from arr without replacement, and store the result in the sample variable. We then print the sample variable to see the output.

Note that the random.sample() function raises a ValueError if k is larger than the length of the input sequence. So if you want to get a sample of size k from an array with n elements, make sure that k is less than or equal to n.

gistlibby LogSnag