Main Content

Python generator functions, lambdas, and iterators

Archive - Originally posted on "The Horse's Mouth" - 2005-04-28 08:31:53 - Graham Ellis

Python provides a number of useful "extras" on functions and methods beyond what's basically needed in a cruder language. But some of the names / facilities can confuse. Here's some clarification

Lambdas

A Lambda is a function written in a single line in Python - rather like an anonymous function in Perl

Generators

A Generator is a function which doesn't do all of its work at once. Rather, it works until it has worked out part of what it has to return which it then passes back through the yield keyword ... and it then resumes when required to work out the next return value

Iterators

An iterator is returned by a generator function - in other works, it's Python's mechanism through which a fucntion can be used to "drip feed" the results back to a calling program rather that have it fed back all at once.

You would use a generator to produce an iterator if you had a huge amount of data to handle. If you're looking for a simile (or is that a metafore?), you could compare a regular function call like asking for a bucket of water (and that will quickly get very heavy) and you could compare a generator function to being rather like having a tap on the end of a pipe which you can turn on and off and get as much water as you need (no real limit) all in manageable quantities.

You'll find some code examples linked from our Functions and Modules in Python training section. We have Python courses available too.