Is it possible to create a python nested loop that returns two array entries for each cycle of the loop?
For example I can have this output from this nested loop:
>>> [x for x in [1,2,3,4,5,6]]
[1, 2, 3, 4, 5, 6]
How can I create a single-line nested loop that would return me something like (the array for loop should stay like [1,2,3,4,5,6]):
[99, 1, 99, 2, 99, 3, 99, 4, 99, 5, 99, 6]
Where for each cycle inside the loop I would also inject an extra value. Is this possible or my only solution would be to expand this nested loop into a normal loop with two appends?
I want to avoid having this:
myArray = []
for x in [1,2,3,4,5,6]:
myArray.append(99)
myArray.append(x)
>Solution :
It is possible, but unfolding it in 3 lines might be more readable, and therefore a better option than a list comprehension:
You have to use:
- one way to repeatedly generate the constant value you want to interleave. – this can be done with
itertools.repeat; - pack both values together for each iteration: the builtin
zipdoes that; - iterate the packed values: the one coming from your normal source and the one injected: you need another
forstatement. I find it a bit counterintuitive that in comprehensions, nested loops are just nested as in normal code, but the expression making use of the loop values (v) in this case, is in the outermost part, as a prefix:
from itertools import repeat
result = [v for bundle in zip(repeat(99), [1,2,3,4,5]) for v in bundle]