Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension with several elements per entry

This one is clear:

a = ['a', 'b', 'c']
x = [v for v in a]

But I am not sure how to do this:

sep = 5
# ??? y = [v + sep for v in a]
print y # expected ['a', 5, 'b', 5, 'c', 5]

How can I write a list comprehension with multiple elements per source element?

I am not interested in optimizations of this code: please do not refer to the [:] operator or join method or something on those lines. My code needs a list comprehension. The only alternative I have at the moment is a 4 lines for loop, which is inconvenient:

y = []
for v in a:
    y.append(v)
    y.append(sep)
like image 417
blueFast Avatar asked Feb 03 '26 17:02

blueFast


2 Answers

Using nested list comprehension:

>>> a = ['a','b','c']
>>> [item  for x in a for item in (x, 5)]
['a', 5, 'b', 5, 'c', 5]
like image 144
falsetru Avatar answered Feb 06 '26 05:02

falsetru


You can build a list of tuples first, and then flatten the resulting list using itertools.chain.from_iterable:

>>> sep = 5
>>> a = ['a', 'b', 'c']
>>> 
>>> import itertools
>>> list(itertools.chain.from_iterable((elem, sep) for elem in a))
['a', 5, 'b', 5, 'c', 5]
like image 45
Rohit Jain Avatar answered Feb 06 '26 06:02

Rohit Jain