1

I want to create a random list, but none of the numbers in the list can have the same value. and only numbers from 0 to 9

I have tried random.randint, random.choice, random.randrage, even tried: random.randint(0 > value < 9)

number = [random.randint(0,9),random.randint(0,9),random.randint(0,9),random.randint(0,9)]

for index,value in enumerate(number):
    values = [0,1,2,3,4,5,6,7,8,9]
    values.remove(value)
    if value == number[index-1] or number[index-2] or number[index-3]:
        number[index] = random.choice(values)


print(number)

i want to get a list of four numbers which are not duplicates, but i keep on getting duplicates?

Vilmer
  • 25
  • 5

2 Answers2

0

You are looking for random.sample:

>>> random.sample(range(0,10), 4)
[9, 6, 2, 0]

The values are chosen without replacement, so there are no duplicates in output list. Because of this, a request for a sample larger than the input sequence will raise a ValueError instead.

chepner
  • 497,756
  • 71
  • 530
  • 681
0
from random import sample

my_list = sample(range(10),4)

print(my_list)

Replace range(10) with whatever list you want to grab a random sample from in the future.

S Hanson
  • 168
  • 1
  • 2
  • 10
  • Bruh, if I knew the answer was that easy, I wouldnt have gone through the long process of writing all that code... but thanks for the answer – Vilmer Jun 10 '19 at 19:40