Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects between objects python

Tags:

python

list

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?

like image 395
iam_agf Avatar asked Apr 30 '26 10:04

iam_agf


2 Answers

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))
like image 183
Steve Jessop Avatar answered May 03 '26 00:05

Steve Jessop


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]
like image 43
thefourtheye Avatar answered May 03 '26 00:05

thefourtheye