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

Create Python alternating range programmatically

I am looking for a convenient way to create an ordered, alternating (negative, positive while decrementing and incrementing by one from previous pair) list of integers in the form of

[-1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10]

with Python with variable length/end integer, like:
alternating_range(2) = [-1, 1, -2, 2]

I can easily do this in a "for loop" but I am looking for a more "Pythonic" way

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

>Solution :

You could do it as a generator like this:

def alternating_range(x):
    return (i for j in range(1, x+1) for i in (-j,j))

However, I think the for loop solution is more readable. You cite "flat is better than nested". This solution has only one level of nesting while the one above has 2.

def alternating_range(x):
    for i in range(1, x+1):
        yield -i
        yield i

Both of these return generators, you can use list(alternating_range(x)) to convert to a list.

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