#coding:utf-8
# Build and return a list
def firstn_func(n):
    num, nums = 0, []
    while num < n:
        nums.append(num)
        num += 1
    return nums
#problème : toute la liste est chargée en mémoire !

#solutions: iterateur ou générateur
class firstn_iterator(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()

def firstn_generator(n):
    num = 0
    while num < n:
        yield num
        num += 1

if __name__ == '__main__':
    sum_of_first_n = sum(firstn_func(1000000))
    sum_of_first_n = sum(firstn_iterator(1000000))
    sum_of_first_n = sum(firstn_generator(1000000))