Reputation: 4168
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.
Upvotes: 6
Views: 3032
Reputation: 6179
You already have
l = [['a', 'foo'], ['a', 'bar], ['a', 'baz']]
You can flatten it using
[item for sublist in l for item in sublist]
this even works for arbitrary length nested list.
Upvotes: 2
Reputation: 309841
A simple generator function works nicely here too:
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')
This lets you avoid a nested list-comprehension and is quite straight-forward to read and understand at the cost of being slightly more verbose.
Upvotes: 3
Reputation: 1121486
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))
Upvotes: 13