Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

481
Views
Generate random number in range excluding some numbers

Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range?

For example, I know that you can generate a random number between 0 and 9 with:

from random import randint
randint(0,9)

What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try this:

from random import choice

print choice([i for i in range(0,9) if i not in [2,5,7]])
over 4 years ago · Santiago Trujillo Report

0

Try with something like this:

from random import randint

def random_exclude(*exclude):
  exclude = set(exclude)
  randInt = randint(0,9)
  return my_custom_random() if randInt in exclude else randInt 
  
print(random_exclude(2, 5, 7))
over 4 years ago · Santiago Trujillo Report

0

If you have larger lists, i would recommend to use set operations because they are noticeable faster than the recomended answer.

random.choice(list(set([x for x in range(0, 9)]) - set(to_exclude)))

I took took a few tests with both the accepted answer and my code above.

For each test i did 50 iterations and measured the average time. For testing i used a range of 999999.

to_exclude size 10 elements:
Accepted answer = 0.1782s
This answer = 0.0953s

to_exclude size 100 elements:
Accepted answer = 01.2353s
This answer = 00.1117s

to_exclude size 1000 elements:
Accepted answer = 10.4576s
This answer = 00.1009s

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!