Q:

Yielding alternate values in iterables

I am given a number of iterables , I need to produces all the values in the first iterable, followed by all in the second, ... , all values in the last iterable alternatively. 
Example :
for i in alternate('abcde','fg','hijk'): 
      print(i,end=' ')

It is expected to produce the values
a f h b g i c

I know to print all the characters in sequence like
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'

Here is the code:
def alternate(*args):
    for iterable in args:
        for item in iterable:
            yield item

But how do I yield them alternatively?

A:

If you want to terminate on shortest list use zip:

Make an iterator that aggregates elements from each of the iterables.

def alternate(*args):
    # note: python 2 - use izip_longest
    for iterable in zip(*args):
        for item in iterable:
            if item is not None:
                yield item

If you want to use all items use itertools.izip_longest:

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue.

def alternate(*args):
    # note: python 2 - use izip_longest
    for iterable in itertools.zip_longest(*args):
        for item in iterable:
            if item is not None:
                yield item

Note that it skips None values (can be changed with fillvalue).
Without itertools:
def alternate(*args):
    max_len = max(map(len, args))
    for index in range(max_len):
        for lst in args:
            try:
                yield lst[index]
            except IndexError:
                continue

To stop on first "missing" item:
def alternate(*args):
    index = 0
    while True:
        for lst in args:
            try:
                yield lst[index]
            except IndexError:
                return
        index += 1

And if you're using generators (or iterators) you'll get StopIteration when one of them is done, so you can use iter to create a general function:
def alternate(*args):
    iters = [iter(lst) for lst in args]
    while True:
        for itr in iters:
            try:
                yield next(itr)
            except StopIteration:
                return

