Create Python alternating range programmatically

Advertisements

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

>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.

Leave a Reply Cancel reply