python - Inserting an element before each element of a list -
i'm looking insert constant element before each of existing element of list, i.e. go from:
['foo', 'bar', 'baz']
to:
['a', 'foo', 'a', 'bar', 'a', 'baz']
i've tried using list comprehensions best thing can achieve array of arrays using statement:
[['a', elt] elt in stuff]
which results in this:
[['a', 'foo'], ['a', 'bar'], ['a', 'baz']]
so not want. can achieved using list comprehension? in case matters, i'm using python 3.5.
add loop:
[v elt in stuff v in ('a', elt)]
or use itertools.chain.from_iterable()
zip()
, itertools.repeat()
if need iterable version rather full list:
from itertools import chain, repeat try: # python 3 version (itertools.izip) future_builtins import zip except importerror: # no import needed in python 3 = chain.from_iterable(zip(repeat('a'), stuff))
Comments
Post a Comment