Python Generator Performance, Yield, One Line Generator
Generator Performance
Generators are a great way to optimize memory. An infinite sequence generator is an extreme example of this optimization.
Yield
The yield statement suspends a function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off.
When the function resumes, it continues execution immediately after the last yield run.
This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list in which we optimized memory usage.
One Line Generator
Iterate through a list and brace them in a ()
.
(x for x in [1,2,3,4])
|
|
Output:
one line generator
type(olg) = <class ‘generator’>
olg = <generator object
at 0x0000029BBC2C4B30> 1
2
3
4
Same as
|
|
Output:
1
2
3
4
Function
|
|
Output:
1
2
3
|
|
5
5
5
5
5
5
5
5
5
5
Appendix
Generator of Generators
|
|
https://stackoverflow.com/questions/19033401/python-generator-of-generators
Length of Generator
The easiest way is probably just sum(1 for _ in gen)
where gen is your generator.
https://stackoverflow.com/questions/393053/length-of-generator-output