Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: simple way to increment by alternating values?

I am building a list of integers that should increment by 2 alternating values.

For example, starting at 0 and alternating between 4 and 2 up to 20 would make:

[0,4,6,10,12,16,18]

range and xrange only accept a single integer for the increment value. What's the simplest way to do this?

like image 769
isticism Avatar asked Nov 30 '22 09:11

isticism


2 Answers

I might use a simple itertools.cycle to cycle through the steps:

from itertools import cycle
def fancy_range(start, stop, steps=(1,)):
    steps = cycle(steps)
    val = start
    while val < stop:
        yield val
        val += next(steps)

You'd call it like so:

>>> list(fancy_range(0, 20, (4, 2)))
[0, 4, 6, 10, 12, 16, 18]

The advantage here is that is scales to an arbitrary number of steps quite nicely (though I can't really think of a good use for that at the moment -- But perhaps you can).

like image 187
mgilson Avatar answered Dec 06 '22 20:12

mgilson


You can use a list comprehension and the modulus operator to do clever things like that. For example:

>>> [3*i + i%2 for i in range(10)]
[0, 4, 6, 10, 12, 16, 18, 22, 24, 28]
like image 38
N. Shead Avatar answered Dec 06 '22 22:12

N. Shead