Python Tips & Tricks: Number Counter using Generator [CODE]

Scroll to bottom of the page to play with a Python code with tip and trick. Before, moving to the code I want to give a little information about Python’s Generators.

Python’s Generator functions are very powerful way of improving performance when dealing with a big list of data. Let’s say you want to iterate over list of 1.000.000 items and append each of them to another list:

# Build and return a list
def firstn(n):
    num, nums = 0, []
    while num < n:
        nums.append(num)
        num += 1
    return nums

sum_of_first_n = sum(firstn(1000000))

Here you will keep all of them in memory, but instead of that you can use generator function and generate each next item of the list when it is needed:

class firstn(object):
    def __init__(self, n):
        self.n = n
        self.num, self.nums = 0, []

    def __iter__(self):
        return self

    # Python 3 compatibility
    def __next__(self):
        return self.next()

    def next(self):
        if self.num < self.n:
            cur, self.num = self.num, self.num+1
            return cur
        else:
            raise StopIteration()

sum_of_first_n = sum(firstn(1000000))

So, now about tip and trick. Using following code you can generate a counter step by step:

More about generator functions you can read in official documentation:
https://wiki.python.org/moin/Generators
https://docs.python.org/3/c-api/gen.html

Leave a Reply