# [Tutor] generators

Joel Goldstick joel.goldstick at gmail.com
Tue Apr 3 21:15:46 CEST 2012

```On Tue, Apr 3, 2012 at 2:38 PM, mike jackson <mgjack at gmx.com> wrote:
> I am trying understand python and have done fairly well, So for it has been easy to learn and is concise.  However I seem to not quite understand the use of a generator over a function(I am familiar with functions [other languages and math]).  To me (excepting obvious syntax differences) a generator is a function.  Why should I use a generator instead of a function or vice versa?  Is perhaps specfic uses it was created to handle?  A great web page with good examples would be nice.  Of course if you can sum it up rather easy then by all means go ahead.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

A generator function is a special kind of function that uses the
'yield' statement to return a value.  The next time the function is
called, it starts up from the place following the yield statement.
They are useful in producing the next value in a computed sequence of
values without having to compute the whole sequence at one go.

Here is a great tutorial about things you can do with generators:
http://www.dabeaz.com/generators/

Here is some simple code with results below

#! /usr/bin/env python
""" generator vs normal function"""
""" a 'Normal' function"""
def n(r):
v = []
for i in range(r):
v.append(i*2)
return v

""" A generator function"""
def g(r):
for i in range(r):
yield i*2

print n(3)

for i in g(3):
print i

generated_list = [i for i in g(3)]
print generated_list

[0, 2, 4]
0
2
4
[0, 2, 4]

--
Joel Goldstick
```