Lo-Fi Python

Sep 15, 2022

Retrieve Random Numbers Via Python's random Module + range() Built-in

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!

1
2
3
4
5
6
7
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)[0]
print(number)
Python Random Number Code

To choose a sample from a range of integers, use a range() object as an argument.

"This is especially fast and space efficient for sampling from a large population":

1
sample(range(10000000), k=60)

- Python Docs, https://docs.python.org/3/library/random.html#random.sample