My Coding > Programming language > Python > Python Generators

Python Generators (Page: 1)

Go to Page:

  1. Python generators - basic;
  2. Generator expressions in Python;

About Python Generators

Generators in Python are special functions for generating sequences for iterations, or Python generators are a simple way of creating iterators.

Lets consider few simple list generators

Indefinite integers list generator


def integers():
    i = 1
    while True: 
        yield i
        i += 1
print(list(itertools.takewhile(lambda x: x <= 10, integers())))# 1 2 3 4 5 6 7 8 9 10

Indefinite even integers list generator


def even():
    i = 2
    while True: 
        yield i
        i += 2
print(list(itertools.takewhile(lambda x: x <= 10, integers())))# 2 4 6 8 10

Squares

We can write this function with usage of integers() from before


def squares():
    for i in integers():
        yield i*i

Or we can write it from the scratch with calculating our own sequence


def squares():
    i = 1
    while True: 
        yield i*i
        i += 1

Indefinite prime integers list generator

Please note, this script is not speed optimized, but show you an idea of excluding from the list all integers which can be divided to any integers in range from 2 and square root from our studied integer


def primes():
    i = 2
    while True:
        isprime = True
        for x in range(2, int(i**0.5) + 1):
            if i % x == 0: 
                isprime = False
                break
        if isprime:
            yield i
        i += 1
print(list(itertools.takewhile(lambda x: x <= 15, primes())))# 2, 3, 5, 7, 11, 13

Use filter to call generators

For definition of square function see before


def take(n, seq): #Returns first n values from the given sequence
    seq = iter(seq)
    result = []
    try:
        for i in range(n):
            result.append(next(seq))
    except StopIteration:
        pass
    return result

print(take(5, squares())) # prints first 5 squares [1, 4, 9, 16, 25]
print(take(6, primes()))  # prints first 6 prime numbers [2, 3, 5, 7, 11, 13]

Go to Page: 1; 2;


Published: 2021-09-25 11:31:46
Updated: 2021-10-12 10:39:24

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.