There are usually many ways to do most things in Python. I’ve retrieved random numbers a few different ways at various times within the random module, often after reading a Stack Overflow post. This time in my most recent search for random digits, I discovered in the Python docs the random.sample() function with its k parameter:
Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.https://docs.python.org/3/library/random.html#random.sample
When combined with the range() built-in, it makes doing this easy. Being able to specify a length and return a list of random numbers is mighty convenient. This function seems a Pythonic way to randomize to me. Have a look!
import random # Returns a list of 5 random numbers. numbers = random.sample(range(10000000), k=5) print(numbers) # Returns a single random number. number = random.sample(10000000), k=1) print(number)
To choose a sample from a range of integers, use ahttps://docs.python.org/3/library/random.html#random.sample
range()object as an argument. This is especially fast and space efficient for sampling from a large population: