5 Best Ways to Generate Random Numbers within a Given Range and Store in a List in Python

πŸ’‘ Problem Formulation: You want to generate a list of random numbers within a specified range in Python. For example, you may want to create a list containing 10 random numbers between 1 and 50. The expected output is a Python list, such as [14, 29, 39, 7, 35, 22, 17, 3, 47, 18], where each element is a unique random number within the given range.

Method 1: Using random.randint() in a loop

This method involves using a for loop along with the random.randint() function to generate random numbers and store them in a list. It provides a straightforward approach to generate a specific count of random numbers within a desired range.

Here’s an example:

import random

random_numbers = []
for _ in range(10):
    random_number = random.randint(1, 50)
    random_numbers.append(random_number)

print(random_numbers)

Output:

[23, 19, 8, 47, 34, 39, 29, 10, 5, 16]

This code snippet imports the random module and initializes an empty list. Then, it iterates 10 times, generating a random number within the range of 1 to 50 during each iteration. This random number is then appended to the list. Note that each execution will yield a different set of random numbers.

Method 2: Using list comprehension with random.randint()

List comprehension in Python is a succinct way to create lists. Combining list comprehension with random.randint() provides an elegant one-liner solution to generate random numbers within a specified range and store them in a list.

Here’s an example:

import random

random_numbers = [random.randint(1, 50) for _ in range(10)]

print(random_numbers)

Output:

[42, 28, 7, 21, 37, 14, 3, 35, 11, 30]

In this snippet, we use a list comprehension that runs a loop 10 times, calling random.randint(1, 50) for each iteration and collecting the results in a new list. It’s a more Pythonic and concise way to achieve the same result as Method 1.

Method 3: Using random.sample()

The random.sample() function is used when you need to generate a list of unique random numbers. This method ensures there are no duplicates in the list, which can be particularly useful for scenarios like lottery draws or unique ID generation.

Here’s an example:

import random

random_numbers = random.sample(range(1, 51), 10)

print(random_numbers)

Output:

[2, 44, 37, 23, 13, 50, 31, 7, 42, 14]

This code makes use of the random.sample() function to pick 10 unique numbers from a range of 1 to 50. Note that the range second parameter needs to be one greater than our upper limit to be inclusive. This method returns non-repeating numbers, which may or may not be desired based on your use case.

Method 4: Using numpy.random.randint()

NumPy, a library for numerical operations in Python, provides the numpy.random.randint() function. It’s particularly optimized for generating large arrays of random numbers and is much faster than the pure Python approach when dealing with large datasets.

Here’s an example:

import numpy as np

random_numbers = list(np.random.randint(1, 51, size=10))

print(random_numbers)

Output:

[18, 2, 34, 17, 25, 33, 48, 4, 36, 15]

In the snippet, the np.random.randint() function generates a NumPy array of 10 random integers between 1 and 50, which is then converted to a Python list using the list() function. This method works well for high performance and large scale random number generation tasks.

Bonus One-Liner Method 5: Using random.choices()

If needing duplicates in your randomly generated list is not a concern, random.choices() function is a suitable one-liner. It also allows for weighting of the random numbers if needed.

Here’s an example:

import random

random_numbers = random.choices(range(1, 51), k=10)

print(random_numbers)

Output:

[22, 14, 1, 49, 3, 3, 31, 22, 39, 31]

This snippet elegantly generates a list of 10 random numbers, possibly with duplicates, from 1 to 50 using random.choices(). The key argument k specifies the number of random choices to make. It’s concise and allows for additional complexity such as weighted probabilities.

Summary/Discussion

  • Method 1: Loop with random.randint(). Straightforward. May contain duplicates. Not as efficient for very large lists.
  • Method 2: List Comprehension with random.randint(). Concise. May contain duplicates. Pythonic syntax and still not as efficient for massive lists.
  • Method 3: random.sample(). Ensures uniqueness. Quick and efficient for small ranges but is limited by the size of the input range.
  • Method 4: numpy.random.randint(). Optimized for performance. Ideal for numerical computations and large arrays. Requires NumPy installation.
  • Bonus Method 5: random.choices(). Allows duplicates and weighted options. Simple one-liner. Not suitable when unique items are needed.