Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wp-youtube-lyte domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wordpress/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wordpress-seo domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wordpress/wp-includes/functions.php on line 6114
Infinite random number generator expressions in Python - The Grok Shop

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 *