Jukurrpa Jukurrpa - 3 months ago 7
Python Question

Inserting an element before each element of a list

I'm looking to insert a constant element before each of the existing element of a list, i.e. go from:

['foo', 'bar', 'baz']


to:

['a', 'foo', 'a', 'bar, 'a', 'baz']


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

[['a', elt] for elt in stuff]


Which results in this:

[['a', 'foo'], ['a', 'bar], ['a', 'baz']]


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

Answer

Add another loop:

[v for elt in stuff for v in ('a', elt)]

or use itertools.chain.from_iterable() together with zip() and itertools.repeat() if you need an iterable version rather than a full list:

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))