Generators - Python Example

Python is very powerful at creating sequences, though if a long sequence is required, then this may require a significant of RAM. The entire sequence may not be required storing at one. Generators allow a sequence to be created on item at a time.

Example

If we want to sum the multiples of 3 up to 100000, this would take a significant of ram if we stored the entire sequence.
1
2
3
4
5
6
7
8
9
def multiple(n):
    num = 0
    while num < n:
        num += 3
        yield num

sum_of_multiples = sum(multiple(100000))

print (sum_of_multiples)
Returns:
1
1666783335