[Tutor] What is this an example of (and how can i use it?)

Kent Johnson kent37 at tds.net
Mon Sep 21 02:52:24 CEST 2009


On Sun, Sep 20, 2009 at 1:27 PM, kevin parks <kp8 at mac.com> wrote:
>
> On Sep 21, 2009, at 1:32 AM, Alan Gauld wrote:
>
>> kevin parks wrote:
>>
>>> called, and what it is an example of. I guess there are generators and
>>> iterators now and it seems this might be an example of one of those new
>>
>> This is a generator expression.
>
> That's unfortunate news for me.

Why?

> So... then to call (by call i mean use/execute/doit) i would do, what?
> foo.next()

Are you asking how to use a generator function? There is a simple
example on the recipe page (sorry, I omitted the link earlier)
http://code.activestate.com/recipes/528936/
>>> list(roundrobin('abc', [], range(4),  (True,False)))
['a', 0, True, 'b', 1, False, 'c', 2, 3]

Calling a generator function gives you something that can be iterated.
You can create a list out of it (by passing it to the list() function)
or you can iterate the items in it directly with a for loop. Using the
example above, you could say
for item in roundrobin('abc', [], range(4),  (True,False)):
  print item

> I kinda understand conceptually what iterators and generators do and why
> they are "a honking good idea" (why create 100 of x when we just want the
> 100th, etc.) what i don't get is the syntax and how they are used in real
> life. How generator and iterators behave in the wild.

It's really not that bad. They are just a generalization of what you
have already been doing with lists.

> Even the Lutz is too
> terse and generally poor on these two complex and relatively new constructs.
> They are a dark and obscure magic.

No, really they are not difficult. Read my essay and ask questions if
you don't understand.

Kent


More information about the Tutor mailing list