'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 1:[1]

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)

Solution 2:[2]

for i in range(6):
    a = np.random.randint(10)
    if a < 5:
        List.append(a)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 richardec