Inserting an element before each element of a list
<p>I'm looking to insert a constant element before each of the existing element of a list, i.e. go from:</p>

<pre><code>['foo', 'bar', 'baz']
</code></pre>

<p>to:</p>

<pre><code>['a', 'foo', 'a', 'bar', 'a', 'baz']
</code></pre>

<p>I've tried using list comprehensions but the best thing I can achieve is an array of arrays using this statement:</p>

<pre><code>[['a', elt] for elt in stuff]
</code></pre>

<p>Which results in this:</p>

<pre><code>[['a', 'foo'], ['a', 'bar'], ['a', 'baz']]
</code></pre>

<p>So not exactly what I want. Can it be achieved using list comprehension? Just in case it matters, I'm using Python 3.5.</p>

<p>A simple generator function works nicely here too:</p>

<pre><code>def add_between(iterable, const):
    # TODO: think of a better name ... :-)
    for item in iterable:
        yield const
        yield item

list(add_between(['foo', 'bar', 'baz'], 'a')
</code></pre>

<p>This lets you avoid a nested list-comprehension and is quite straight-forward to read and understand at the cost of being <em>slightly</em> more verbose.</p>

python list python-3.x list-comprehension