I have a for loop that looks like this, and am looking to make it faster.
mylist = range(100)
def normalrandom():
for a in range(100):
b = random.getrandbits(1)
if b==1: #do something with mylist[a]
My list has ~100 elements, and I know calls to random are expensive. Is there a faster way to make just one call to random, and get 100 random booleans?
Edit: Here is the best solution so far.
def fastrandom():
s = list(range(100))
res = [i for i in s if random.random() >= .5]
for item in res:
#do something with mylist[item]
- normalrandom: 0:00:00.591000
- fastrandom: 0:00:00.293000