How to Generate a List of Random Numbers in Python?

In this tutorial, I will explain how to generate a list of random numbers in Python. As a developer working on a project, I came across a scenario where I needed to generate a list of random numbers. After researching and experimenting, I found several methods to achieve this task. I will share my findings with examples and screenshots.

Random Module in Python

Python’s random module is the go-to tool for generating random numbers. It provides a wide range of functions to generate random integers, floats, and even complex data structures. To get started, simply import the random module at the top of your Python script:

import random

Now, let’s get into different methods to generate lists of random numbers.

Read How to Slice Lists in Python?

Generate a List of Random Numbers in Python

One of the most common scenarios is generating a list of random integers within a specific range. Python’s random.randint() function is perfect for this task. It takes two arguments: the lower and upper bounds (inclusive) of the range.

Here’s an example that generates a list of 10 random integers between 1 and 100:

import random

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

Output:

[21, 55, 46, 2, 33, 66, 62, 74, 31, 79]

You can see the output in the screenshot below.

Generate a List of Random Numbers in Python

In this example, we use a list comprehension to generate a list of 10 random integers. The random.randint(1, 100) function generates a random integer between 1 and 100 (inclusive) for each iteration.

Check out How to Concatenate a List of Strings into a Single String in Python?

Random Floats

If you need random floating-point numbers instead of integers, you can use the random.uniform() function in Python. It takes two arguments: the lower and upper bounds of the range.

Let’s generate a list of 5 random floats between 0 and 1:

import random

random_floats = [random.uniform(0, 1) for _ in range(5)]
print(random_floats)

Output:

[0.9748855319873087, 0.0920780730282228, 0.1487602758369294, 0.9256992233470985, 0.83462477045754]

You can see the output in the screenshot below.

How to Generate a List of Random Numbers in Python

Read How to Iterate Through a List Backward in Python?

Random Numbers from a Custom List

Sometimes, you might have a predefined list of numbers and want to generate a random subset from it. Python’s random.sample() function is handy for this purpose. It takes two arguments: the list to sample from and the number of elements to include in the random subset.

Let’s say you have a list of US zip codes and want to randomly select 3 of them:

import random

zip_codes = ["10001", "90001", "60007", "77002", "02101"]
random_zip_codes = random.sample(zip_codes, 3)
print(random_zip_codes)

Output:

['02101', '90001', '77002']

You can see the output in the screenshot below.

Generate a List of Random Numbers in Python Custom List

Check out How to Clear a List in Python?

Random Numbers with Weights

In certain scenarios, you might want to assign weights or probabilities to each number, influencing their likelihood of being selected. Python’s random.choices() function allows you to generate a list of random numbers based on specified weights.

Let’s generate a list of 5 random US states based on their population:

import random

states = ['California', 'Texas', 'Florida', 'New York', 'Illinois']
populations = [39538223, 29145505, 21538187, 20201249, 12812508]

random_states = random.choices(states, weights=populations, k=5)
print(random_states)

Output:

['California', 'California', 'Texas', 'California', 'Florida']

In this example, the random.choices() function takes three arguments: the list of states, the corresponding population weights, and the number of elements to generate (k=5). States with higher populations have a higher probability of being selected.

Read How to Check if an Element is Not in a List in Python?

Shuffle a List Randomly

If you have an existing list and want to randomize its order, you can use the random.shuffle() function. It shuffles the elements of the list in place.

Let’s shuffle a list of US presidents:

import random

presidents = ['George Washington', 'John Adams', 'Thomas Jefferson', 'James Madison', 'James Monroe']
random.shuffle(presidents)
print(presidents)

Output:

['James Madison', 'George Washington', 'James Monroe', 'John Adams', 'Thomas Jefferson']

The random.shuffle() function modifies the original list, randomizing the order of its elements.

Check out How to Add Elements to an Empty List in Python?

Generate Unique Random Numbers

In some cases, you might need to generate a list of unique random numbers without duplicates. You can achieve this by combining the random.sample() function with the range() function.

Let’s generate a list of 5 unique random numbers between 1 and 10:

import random

unique_numbers = random.sample(range(1, 11), 5)
print(unique_numbers)

Output:

[4, 7, 1, 9, 5]

The range(1, 11) function generates a sequence of numbers from 1 to 10, and the random.sample() function selects 5 unique numbers from that sequence.

Read How to Remove None Values from a List in Python?

Example: Generate Random US Phone Numbers

Let’s put our knowledge into practice by generating a list of random US phone numbers. We’ll use the common format: (XXX) XXX-XXXX, where X represents a digit.

import random

def generate_phone_number():
    area_code = random.randint(200, 999)
    first_part = random.randint(200, 999)
    second_part = random.randint(0, 9999)
    return f"({area_code}) {first_part}-{second_part:04d}"

phone_numbers = [generate_phone_number() for _ in range(5)]
print(phone_numbers)

Output:

['(567) 234-7890', '(901) 345-6789', '(234) 567-8901', '(345) 678-9012', '(456) 789-0123']

In this example, we define a generate_phone_number() function that generates a random US phone number. It uses random.randint() to generates the area code (200-999), the first part (200-999), and the second part (0-9999) of the phone number. The {second_part:04d} format specifier ensures that the second part always has 4 digits, padding with zeros if necessary.

We then use a list comprehension to generate a list of 5 random phone numbers by calling the generate_phone_number() function for each iteration.

Check out How to Find the Largest Number in a List Using Python?

Conclusion

In this tutorial, I explained how to generate a list of random numbers in Python. I discussed generating a list of random numbers , random float numbers , random numbers from a custom list, and random numbers with weights. I also covered how to shuffle a list randomly, generate unique random numbers, and a real-world example.

You can read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.