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.
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.
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 .
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.
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'] .
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With