Python Generator Expressions

In Python, you can do a list comprehension (short list builder) which is really efficient:

[ val for val in biglist ]

You can do the same thing with dictionaries:

{ x.val: x.val2 for x in biglist }

The Feature that Changed My Life

You can take that inner statement “val for val in biglist” and package it up into a reusable generator expression!

mygenerator = ( val for val in someiterable )

Then, you can pass that generator around to other functions. Each call will run the generator once, return a value, and then wait until it is told to iterate again. The crazy part is, I knew that this is how the yield statement worked in Python to create generator functions (functions using yield return a generator). I had never thought of this flip side of generators functions packaged up all nice and neatly.

Continue reading “Python Generator Expressions”

Advertisements
Python Generator Expressions