Most Pythonique, Efficient, Compact, and Elegant Way to Do This

Given a list of strings, how would you iterpolate a multi-character string in front of each element? For example, given:

    >>> k = ['the quick', 'brown fox', 'jumps over', 'the lazy', 'dog']

The objective is to get:

    ['-c', 'the quick', '-c', 'brown fox', '-c', 'jumps over', '-c', 'the lazy', '-c', 'dog']

Of course, the naive solution would be to compose a new list by iterate over the original list:

    >>> result = []
    >>> for i in k:
    ...     result.append('-c')
    ...     result.append(i)

Alternatively, you could take advantage of the itertools module:

    >>> import itertools
    >>> result = list(itertools.chain.from_iterable(itertools.product(['-c'], k)))

This second form is certainly more compact, and probably more efficient … but perhaps lacks some of the clarity and elegance one might expect from Python. Is there another solution?

Share