Search code examples
pythonpython-2.7cycle

Oscillating Values in Python


So I need to have 2 values oscillate back and forth. Say 2 the first time, and 4 the second time. Repeat from the top.

So I wrote the below generator function which works. Each time it is called via next it returns the subsequent value, and then repeats from the top.

For the sake of learning, and improving, NOT opinion, is there a better way? In Python there always seems to be a better way, and I like to learn them so as to improve my skills.

The "main code" is just to show an example of the generator, oscillator, in use, and is not the primary use of the oscillator.

## Main code
go_Osci = g_Osci()
for i in xrange(10):
    print("Value: %i") %(go_Osci.next())

## Generator
def g_Osci():
    while True:
        yield 2
        yield 4

Solution

  • Yes, there is a better way. itertools.cycle was designed explicitly for this task:

    >>> from itertools import cycle
    >>> for i in cycle([2, 4]):
    ...     print i
    ...
    2
    4
    2
    4
    2
    4
    2
    # Goes on forever
    

    You can also use enumerate to only cycle a certain number of times:

    >>> for i, j in enumerate(cycle([2, 4])):
    ...     if i == 10:  # Only loop 10 times
    ...         break
    ...     print j
    ...
    2
    4
    2
    4
    2
    4
    2
    4
    2
    4
    >>>