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>Add another loop:</p>

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

<p>or use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable"><code>itertools.chain.from_iterable()</code></a> together with <a href="https://docs.python.org/3/library/functions.html#zip"><code>zip()</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.repeat"><code>itertools.repeat()</code></a> if you need an iterable version rather than a full list:</p>

<pre><code>from itertools import chain, repeat
try:
    # Python 3 version (itertools.izip)
    from future_builtins import zip
except ImportError:
    # No import needed in Python 3

it = chain.from_iterable(zip(repeat('a'), stuff))
</code></pre>

python list python-3.x list-comprehension