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))
5
  • 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) Commented Jan 14, 2018 at 3: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. Commented Jan 14, 2018 at 3:53
  • @Ajax1234 Yes agreed. Commented Jan 14, 2018 at 3:54
  • In your case you can probably pick only 1 random element and leave that one out, or does order matters? Commented Jan 14, 2018 at 4:08
  • Does this answer your question? Generate 'n' unique random numbers within a range Commented Jan 21, 2022 at 11:45

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.