My Coding > Programming language > Python > Python Generators

Python Generators (Page: 2)

Go to Page:

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

Generator expressions in Python

Generator expressions are generator version for list comprehensions, but return generator instead of list.


a = (x*x for x in range(10))  # define generator of list of squares
print( a )                    #  at 0x7fc2a414cd00>
print( type(a) )              # 

It is important to understand, that this generator will only be executed when it will be used, and after its iterator will be pointed to the end of its generating values


a = (x*x for x in range(10))  # we define generator of ten squares here
l1=list(a)                    # call generator and store everything into a list
print( l1 )                   # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
l2=list(a)                    # call again this generator, but it is already 'used'
print( l2 )                   # []

One more example of usage of this 10 squares generator


sq = (x*x for x in range(10)) # we define generator of ten squares here
print( sum(sq) )              # 285
print( sum(sq) )              # 0 - it is already 'used'

List of pythogorian triplets with generators

Very simple task is to find N pythogorian triplets with generator. Pythogorian triplets and a triplets of integers (x,y,z) where

x*x + y*y == z*z; or x**2 + y**2 == z**2

Please go to Page 1 for definition of out generators integers() and take()


PTgen = ((x, y, z) for z in integers() for y in range(1, z) for x in range(1, y) if x*x + y*y == z*z)
tr = take(5, PTgen) # we will generate 20 triangles
print( tr )         # [(3, 4, 5), (6, 8, 10), (5, 12, 13), (9, 12, 15), (8, 15, 17)]          

You can use generator one by one with function next(). In this case generator will remenr it's iteration


sq = (x*x for x in integers()) # See previous page for integers() definition
print( next(sq) )              # 1
print( next(sq) )              # 4
print( next(sq) )              # 9
print( next(sq) )              # 16

How to join generator into a string

It is possible to join generator into a string with function .join(). It is important to remember that this generator must produce object of STR type.


new_string = '-'.join(str(x) for x in range(10)) # 0-1-2-3-4-5-6-7-8-9

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.