Open In App

Generate a List of Random Numbers Without Duplicates in Python

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

There are a few ways to generate a list of random numbers without duplicates in Python. Let’s look at how we can generate a list of random numbers without any duplicates.

Using random.sample()

This random.sample() method allows us to generate a list of unique random numbers in a single step.

Python
import random

# Generate 5 unique random numbers between 1 and 10
a = random.sample(range(1, 11), 5)

print(a)

Output
[8, 3, 6, 10, 5]

Other methods which can help us to generate list of random numbers without duplicates in python are:

Using random.shuffle()

A more advanced method is to generate a list of number then shuffle it and then pick the first few numbers. random.shuffle() method works well when we want to avoid using loops or manual checks.

Python
import random

a = list(range(1, 11))  # Create a list of numbers from 1 to 10
random.shuffle(a)  # Shuffle the list
a = a[:5]  # Get the first 5 numbers from the shuffled list

print(a)

Output
[7, 8, 9, 5, 6]

Using numpy's random.choice() with replace=False

If we are working with large arrays or need more advanced random number generation, we can use numpy. The random.choice() function can be used to select unique values if replace=False.

Python
import numpy as np

# Generate 10 unique random numbers from 1 to 100
a = np.random.choice(range(1, 101), size=10, replace=False)
print(a)

Output
[ 5 92 42 76 91 22 75 69 63 33]

Using while Loop

Another simple way to generate random numbers without duplicates is by using a while loop to keep adding random numbers to a list until we have enough unique numbers. We can check for duplicates by using a set.

Python
import random

a = []
while len(a) < 5:
    num = random.randint(1, 10)
      # Check if the number is already in the list
    if num not in a:
        a.append(num)

print(a)

Output
[1, 2, 4, 6, 5]

Next Article
Article Tags :
Practice Tags :

Similar Reads