Tommy Kay
Tommy Kay

Reputation: 103

How to get non repeating random integers

I am trying to get numbers between 0 and 25 assigned to 26 things on a list but cannot be repeated I am assuming that you would use and if and else statement but this is what I have so far

def f():
    a=[0]*26
    for x in a:
        b=randrange(0,26)
        a[b]=randrange(0,26)
    return(a)
print(f()) 

Upvotes: 1

Views: 682

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62888

Make a list of numbers 0..25 and shuffle it:

>>> import random
>>> a = list(range(26))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25]
>>> random.shuffle(a)
>>> a
[11, 3, 17, 0, 20, 13, 24, 21, 4, 12, 14, 1, 22, 18, 5, 8, 6, 10, 9, 25, 23, 19,
 16, 7, 2, 15]

Upvotes: 2

Related Questions