Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python nested loop with two outputs in a single-line

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]):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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 zip does that;
  • iterate the packed values: the one coming from your normal source and the one injected: you need another for statement. 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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading