7

I want to generate a random number, and that random number should be unique, meaning it should not be repeated or generated again. I have tried making a list where I append in every iteration and check if it is already present in the list or not. If it is present in the list, the number is not appended. But I don't think it is an effective method. So, please help me with it.

    import random
    #an empty list to append randomly generated numbers
    empty = []
    while True:
        #checking from range 500 to 510
        number = random.randrange(500, 510)
        if number not in empty:
            empty.append(number)
        else:
            pass
        #breaking the loop if the length of the numbers is 9
        if len(empty) == 9:
            break

    print("Final list --> " + str(empty))
Bibek Bhandari
  • 422
  • 1
  • 4
  • 15
  • 1
    You should generate a list of all random numbers you need and then shuffle them. Otherwise you will need to keep generating random numbers until you get one that isn't in the list (which is very time consuming for large lists of numbers) – Jessie Jan 14 '18 at 03:50
  • @GarbageCollector in the scope of this problem, the values would be unique because the shuffle function would be passed the range of values needed by the OP, which are all unique. – Ajax1234 Jan 14 '18 at 03:53
  • @Ajax1234 Yes agreed. – Sohaib Farooqi Jan 14 '18 at 03:54
  • In your case you can probably pick only 1 random element and leave that one out, or does order matters? – Elmex80s Jan 14 '18 at 04:08
  • Does this answer your question? [Generate 'n' unique random numbers within a range](https://stackoverflow.com/questions/22842289/generate-n-unique-random-numbers-within-a-range) – Tomerikoo Jan 21 '22 at 11:45

2 Answers2

25

You can get such a list of a given number of non-repeating elements taken from a given pool via random.sample:

>>> random.sample(range(500, 510), 9)
[500, 501, 503, 502, 505, 507, 508, 506, 504]
user2390182
  • 72,016
  • 6
  • 67
  • 89
0
import random
low=int(input("ENTER LOWER RANGE:"))
upper=int(input("ENTER UPPER RANGE:"))
l=[low]
count=1
l=[low]
count=1
if (upper-low)>=c or c==upper:
    while count!=c:
        x=random.randint(low,upper)
        if x not in l:
        l.append(x)
        count+=1

for i in range(len(l)):
    print(l[i])