How to pick a random number not in a list in Python?

PythonServer Side ProgrammingProgramming

The way to go about it is to keep generating a random number in a range till it is not found in a given list. Use randrange() function from randome module to generate random number and check if it is in list by not in membership operator

>>> l1=[2,4,7]
>>> while True:
        x=random.randrange(1,10)
        if x not in l1:break
>>> x
6
raja
Updated on 02-Mar-2020 09:56:26

Advertisements