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)
Using nested list comprehension:
>>> a = ['a','b','c']
>>> [item for x in a for item in (x, 5)]
['a', 5, 'b', 5, 'c', 5]
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]
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