Простой генератор

Списки и коллекции / Итераторы и генераторы

from itertools import islice


def counter(low, high, step):
    current = low
    while current <= high:
        yield current
        current += step


# One value per turn, made on demand
for number in counter(3, 9, 2):
    print(f"{number = }")


# No end condition: it never finishes by itself
def powers_of_two():
    current = 1
    while True:
        yield current
        current *= 2


# islice cuts the endless generator
first_five = list(islice(powers_of_two(), 5))
# first_five is [1, 2, 4, 8, 16]

print(f"{first_five = }")