Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 906
Jukurrpa Avatar asked Sep 07 '16 17:09

Jukurrpa


People also ask

How do you add items to the front of a list in Python?

insert(index, value)this inserts an item at a given position. The first argument is the index of the element before which you are going to insert your element, so array. insert(0, x) inserts at the front of the list, and array. insert(len(array), x) is equivalent to array.

How do you add an element to the beginning of a list?

Use insert() to Append an Element to the Front of a List in Python. The insert() function inserts an element to the given index of an existing list. It accepts two parameters, the index to be inserted into and the value to insert. For example, we'll insert an element into an existing list of size 5 .

How do you add items to the middle of a list in Python?

insert() Method. Use the insert() method when you want to add data to the beginning or middle of a list. Take note that the index to add the new element is the first parameter of the method.

How do you insert an item into a list at a specific index?

You can use the insert() method to insert an item to a list at a specified index. Each item in a list has an index. The first item has an index of zero (0), the second has an index of one (1), and so on. In the example above, we created a list with three items: ['one', 'two', 'three'] .


1 Answers

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))
like image 83
Martijn Pieters Avatar answered Sep 19 '22 02:09

Martijn Pieters