Infinite random number generator expressions in Python

In Python, we can use the random library to get a random number like so:

from random import *
x = randint(1, 100)
print(x)

or maybe you only want an odd number:

from random import *
x = randrange(1, 100, 2)
print(x)

But what if you want an infinite stream of random odd numbers available to you?

from random import *

def infinite_seq():
    while True:
        yield randrange(1, 100, 2)

# Hello, infinite loop!
for num in infinite_seq():
    print(num)

infinite_seq() returns a generator that we can iterate over forever.

And if you’re a little short on space, here’s a one-liner which will do the same job as the 5 lines above:

for num in (randrange(1, 100, 2) for x in iter(int, 1)): print(num)

(randrange(1, 100, 2) for x in iter(int, 1)) is a generator expression.   The syntax is very similar to a list comprehension, but with the parens instead of the square brackets.  This particular generator expression is like an infinite list which uses very little memory.   Of course, one of the great use cases for generators is that they have a relatively tiny memory footprint.

Sharing is caring!

Leave a Comment

Your email address will not be published. Required fields are marked *


Notice: Undefined index: total_count_position in /var/www/wordpress/wp-content/plugins/social-pug/inc/functions-frontend.php on line 46
shares