def first_n(iterable, n, default=None):
    """Generate first n elements of iterable, filling with `default` if
       necessary.

       >>> it = (1,2,3)
       >>> for n in range (6) :
       ...   print (n, tuple (first_n (it, n)))
       ...
       0 ()
       1 (1,)
       2 (1, 2)
       3 (1, 2, 3)
       4 (1, 2, 3, None)
       5 (1, 2, 3, None, None)
    """
    for i, x in enumerate(iterable):
        if i >= n:
            break
        yield x
    for k in range(i + 1, n):
        yield default
