Reputation: 689
I want to make from the list:
L=[1,2,3,4,5,6,7,8,9]
This:
L=[1,1,1,2,1,3,1,4,1,5,1,6,1,7,1,8,1,9]
This is, put the 1 between the objects in list. Can someone help me?
Upvotes: 2
Views: 69
Reputation: 279285
For the result in your example (1 before each object):
L = [y for x in L for y in (1, x)]
For the result described by your text (1 between the objects):
L = [y for x in L for y in (x, 1)]
L.pop()
If you hate multiple for
clauses in comprehensions:
L = list(itertools.chain.from_iterable((1, x) for x in L))
Upvotes: 4
Reputation: 67073
Using itertools:
>>> L=[1,2,3,4,5,6,7,8,9]
>>> from itertools import chain, izip, repeat
>>> list(chain.from_iterable(izip(repeat(1), L)))
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]
Upvotes: 0
Reputation: 1533
A simple for loop would suffice
for item in list:
newList.append(1)
newList.append(item)
list = newList
Upvotes: 1
Reputation: 309959
I've always really loved slice assignment:
>>> L = range(1, 10)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> # Done with setup, let the fun commence!
>>> LL = [None] * (len(L)*2) # Make space for the output
>>> LL[1::2] = L
>>> LL[::2] = [1] * len(L)
>>> LL # Lets check the results, shall we?
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]
Upvotes: 2
Reputation: 239513
print ([i for t in zip([1] * len(L), L) for i in t])
Output
[1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1, 9]
Upvotes: 2