John
John

Reputation: 539

Change list length with comprehension

I'd like to do something like this:

Input: [3, 4, 1, 2]
Output:  ["3", "", "", "4", "", "", "1", "", "", "2", "", ""]

I know that

x = [3, 4, 1, 2]
[str(i) for i in x]

will produce the list without the extra empty strings. My question is whether there's an easy way to make Python go ahead and create 3 output items for each input item in a comprehension. If not, I can certainly write a loop...

Upvotes: 0

Views: 245

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48120

You may also achieve this using zip with list comprehension as:

>>> my_list = [3, 4, 1, 2]
>>> empty_list = [""] * len(my_list)

>>> [i for z in zip(my_list, empty_list, empty_list) for i in z]
[3, '', '', 4, '', '', 1, '', '', 2, '', '']

OR using itertools.chain along with zip as:

>>> from itertools import chain

>>> list(chain(*zip(my_list, empty_list, empty_list)))
[3, '', '', 4, '', '', 1, '', '', 2, '', '']

Upvotes: 1

akuiper
akuiper

Reputation: 215117

Double for loop in list-comprehension acts like map + chain which you can make use of:

[j for i in x for j in [str(i), "", ""]]
# ['3', '', '', '4', '', '', '1', '', '', '2', '', '']

With map and chain syntax, you can do:

from itertools import chain
list(chain.from_iterable([str(i), "", ""] for i in x))
# ['3', '', '', '4', '', '', '1', '', '', '2', '', '']

Upvotes: 5

DYZ
DYZ

Reputation: 57105

You can still use list comprehension, but produce three-string blocks, and later concatenate them:

sum([[str(i), "", ""] for i in x], [])
# ['3', '', '', '4', '', '', '1', '', '', '2', '', '']

Upvotes: 0

Related Questions