Python generators

From wikinotes
Revision as of 20:00, 6 May 2018 by Will (talk | contribs) (→‎Simple Example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Generators in practice work like lists where only one value can be accessed at a time. Similar to classes defining instances, generators are a set of instructions that can be followed repetitively to generate a number.


Generators are more memory-efficient than lists however, because rather than storing an entire massive list of values in memory, when working with generators you are only ever storing the current value, and a chaptermark for which entry in the sequence is your current entry.


Similar to the relationship between classes and objects, generator(objects) are defined by generatorFactory(functions).

Simple Example

def genFactory():					# generator factories are a series of yield statements
	yield 'a'
	yield 'b'
	yield 'c'

Usage:

generator=genFactory()
generator.next()
>>> 'a'
generator.next()
>>> 'b'

Infinite Example

Since generators only store the current value in ram, you can use a generator to pull information from an equation that would generate an infinite amount of return values

def infinite():
	i= 0
	while 1:
		yield i
		i= i + 1