Skip to content

Book recommendation and yielding a generator

January 30, 2013

Recently, a friend referred me to a great book called Writing Idiomatic Python. I would highly recommend it to anyone trying to get better at Python. It goes through a lot a tricks and formalisms that will help you write readable, pythonic code.

Actually, in that book, I finally learned how to properly use the ‘yield’ statement as a generator. The yield statement produces the next value in our generator. I think an example will help. His example is somewhat complicated, so I’m going to go with a very contrived example:

def pows(x):
  out = 1
  while True:
    out *= x
    yield x

We can use that function in the same way we would use any other (infinite) generator: e.g. for x in pows(2.0):. That would allow you to calculate some function of the powers of 2.0 without needing to specify how many powers you are going to calculate.


From → Python tricks

One Comment

Trackbacks & Pingbacks

  1. Calling Your Objects « Partial Lattice

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: