# [Tutor] Alternating patterns

Kent Johnson kent37 at tds.net
Wed Mar 29 15:29:20 CEST 2006

```kevin parks wrote:
>>From: Kent Johnson <kent37 at tds.net>
>>itertools.cycle() will repeat a sequence indefinitely:
>>In [2]: from itertools import cycle
>>
>>In [3]: i=cycle([1,2])
>>
>>In [5]: for j in range(6):
>>    ...:     print i.next()
>>    ...:
>>    ...:
>>1
>>2
>>1
>>2
>>1
>>2
>>
>>For non-repeating sequences I would look at writing a generator
>>function
>>for the sequences.
>>
>>Kent
>
> okay.. i am painfully unaware of generators, iterators, sets, genexes
> and a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that
> i find the online docs kind of terse and few of the Python books yet
> cover these newer constructs in detail....
>
> itertools looks very cool.... are there any toots on the above and on
> Sets & itertools? It really seems like it would help to know these for
> my work... That liddo bit right up there with itertools.cycle already
> has me a drooling... (so helpful that would be!)

The best introduction to new features is usually in the What's New
document accompanying the release where the feature was added. Of course
it helps to know when the feature was added...here are some generator
examples:
http://www.python.org/doc/2.2.3/whatsnew/node5.html

Generators are excellent for encapsulating the generation of a sequence
when there is state that must be maintained between elements. For
example here is a generator that takes a sequence argument, and yields
this sequence of sequences:
the original sequence
the original sequence with the first element incremented by one
the original sequence
the original sequence with the second element incremented by one
etc until each element has been incremented

In [2]: def change_each(seq):
...:     seq = list(seq) # Copy and ensure it's a list
...:     for i in range(len(seq)):
...:         yield seq
...:         seq[i] += 1
...:         yield seq
...:         seq[i] -= 1
...:
...:

In [3]: s = [1, 3]

In [5]: for n in change_each(s):
...:     print n
...:
...:
[1, 3]
[2, 3]
[1, 3]
[1, 4]

If you wanted to repeat this sequence indefinitely you could just wrap
it with itertools.cycle().

The module docs for itertools contain quite a few examples:
http://docs.python.org/lib/itertools-recipes.html

itertools.cycle() is pretty simple, it just loops endlessly over the
sequence you give it.

The itertools docs shows equivalent Python functions for each of the
itertools functions. Most of them are implemented using generator
functions so by looking at them you can learn about itertools and
generators at the same time.
http://docs.python.org/lib/itertools-functions.html

Kent

```