Search code examples
pythonloopsgenerator

Conditional Filtering in Generator with random integer


I would like to create a generator of random numbers.

import numpy as np

rd_list = (np.random.randint(10) for i in range(6))

When I try with this I get values [7, 1, 4, 2, 0, 6].

I would like to filter these results by this condition < 5.

How can I get this result?


Solution

  • Another way using assignment expression (Python 3.8+):

    import random 
    nums = (n for _ in range(6) if (n := random.randint(0, 10)) < 5)
    

    Thanks to Andrej's comment: Since you are already using numpy, you don't need the loop:

    import numpy as np
    
    nums = (n for n in np.random.randint(0, 10, 6) if n < 5)