0
a=[]
from random import randint as rd
for i in range(42):
    a.append(rd(1,42))
    j=0
    k=len(a)-1
    while(j<=k):
        while(a[i]==a[j]):
            a[i]=rd(1,42)
            j=0
        j=j+1

I cannot figure out how to generate entirely unique random lists in python. All the members have to be unique and cannot by any means be the same as any other member of the list

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

2 Answers2

3

Try this:

import random
random.sample(range(100), 10)


In [1715]: random.sample(range(100), 10)
Out[1715]: [66, 48, 97, 5, 39, 67, 78, 96, 71, 19]

In [1716]: random.sample(range(100), 10)
Out[1716]: [50, 89, 60, 69, 81, 86, 27, 94, 4, 62]

This will generate a list of 10 random numbers from the range 0 to 99, without duplicates.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

Use shuffle in that case:

from random import shuffle

random_numbers = list(range(1, 43))
shuffle(random_numbers)

Or, with randint as you tried,

from random import randint as rd

random_numbers = []
for i in range(42):
    r = rd(1, 42)
    while r in random_numbers:
        r = rd(1, 42)

    random_numbers.append(r)
JH Jang
  • 36
  • 3