Generate random numbers in Python without repeating

I have the following situation:

I have a vector with 4 indexes. Each index generates a random value from 0 to 100.

I have a code that does this perfectly, however, sometimes the numbers repeat themselves.

Below the Code:


from random import randint

AP_X = [randint(0, 100), randint(0, 100), randint(0, 100), randint(0, 100)]
print AP_X

I wish that never repeated numbers are generated. For example: [4,4,6,7]

How can I do this?

Author: dot.Py, 2017-04-06

4 answers

You can implement the algorithm this way...

from random import sample

sorteados = sample(range(0, 100), 4)
print(sorteados)

Note that in this code we are using the sample method from the random library. With this method we can draw a number of values without repeating each other.

 1
Author: Solkarped, 2020-09-28 00:05:58
import random
result = random.sample(range(0,100), 4)
 13
Author: Matheus Carvalho, 2017-04-06 11:37:15

Just check if the drawn value no longer belongs to the list, and if it belongs, draw another one. Something like:

result = []
while len(result) != 4:
    r = randint(0, 100)
    if r not in result:
        result.append(r)

This way the code is executed until the list has 4 elements and only a new one is inserted when the same is no longer in the list.

 7
Author: Woss, 2017-04-06 03:01:46

If you are working with dictionaries in python:

aleatorio = randint(1, 6)
test = NomeDict.values()

if aleatorio not in test:
    NomeDict.update({chave: valor})
 -1
Author: Lucas Rocha, 2020-06-29 08:39:34