Insert an item in front of each item in a list

I want to insert a constant element in front of each of the existing list element, i.e. go from:

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

at

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

I tried using lists, but the best I can achieve is an array of arrays using this expression:

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

The result is the following:

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

So not quite what I want. Can this be done using list comprehension? Just in case, this is important; I'm using Python 3.5.

+4
source share
3 answers

Add another loop:

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

or use itertools.chain.from_iterable()with zip()and itertools.repeat()if you need an iterative version, not a complete 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))
+9
source

:

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

.

+3

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

,

[item for sublist in l for item in sublist]

this even works for an arbitrary nested length list.

+1
source

Source: https://habr.com/ru/post/1653937/


All Articles