Python-Ref > Advanced topics > Iterators an generators > Generators
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Generators

How to create functions and methods that act like iterators.
Generators provide Python with the ability to write code that produces list-like data in a lazy fashion.
The code for generators does not differ much from that of normal functions. The only difference visible at first sight is the use the "yield" keyword instead of "return". Both behave in a similar manner, only yield means that one value is returned, but the code may continue afterwards in the next iteration.
The following code shows a typical code that one could use to process all values in a list.
Expand/Shrink
Zdroj: (generator1-1.py)
  1   def multiply_by_n( xs, n):
  2     ret = []
  3     for x in xs:
  4       ret.append( x*n)
  5     return ret
  6   
  7   print multiply_by_n( [1,2,6,8,3,10], 4)
stdout:
[4, 8, 24, 32, 12, 40]
Doba běhu: 25.4 ms
The following code simplifies this example by using a generator.
Expand/Shrink
Zdroj: (generator1-2.py)
  1   def multiply_by_n( xs, n):
  2     for x in xs:
  3       yield x*n
  4   
  5   print multiply_by_n( [1,2,6,8,3,10], 4) # generator is lazy
  6   for y in multiply_by_n( [1,2,6,8,3,10], 4):
  7     print y
  8   
  9   print list( multiply_by_n( [1,2,6,8,3,10], 4))
stdout:
<generator object at 0x2ac07a953fc8>
4
8
24
32
12
40
[4, 8, 24, 32, 12, 40]
Doba běhu: 23.3 ms
Another example of using generators is showed here.