I would like to create a list of x random integers which are chosen from the interval [0,n[ (n is usually much bigger than x) whereby certain numbers of this interval should be ignored. I implemented that as follows:
from random import randint
def createRandomList(n, x, ignore=[]):
myList = []
while len(myList) < x:
tempr = randint(0,n-1)
if tempr not in ignore:
myList.append(tempr)
return myList
When I then call
l = createRandomList(5,2,ignore=[2,3])
I obtain e.g.
l = [1,4] #2 and 3 should not appear
or
l = [0,1]
or
l = [4,4]
or ...
That is the desired outcome, however, is there any faster/more compact way to do this?
EDIT: All of these solutions work fine, so I had to do some speed comparisons to decide which one to accept. It turns out - not very surprisingly - that generating all the allowed values beforehand and then choosing from them, is very inefficient for large values of n and the while-loops win easily. Therefore, I accepted hgwells answer since his version is not only faster than my while-loop but should also consume less memory.
Thanks a lot for all the answers; I could learn a lot from all of them!