Jump to content
Sign in to follow this  
  • entries
    73
  • comments
    131
  • views
    55057

Python #9 - Iterators and Generators

Sign in to follow this  
okonomiyaki

101 views

Iterators

"For" statements in Python internally create iterators that are used to step through the provided sequence.

Python exposes this iteration capability with the "iter()" function. You can pass any kind of collection to "iter" and it returns an iterator object, from which you can call "next()" to retrieve the next element in the collection.

>>> it = iter([1,2,3]);

>>> it.next()
1
>>> it.next()
2
>>> it.next()
3


Not only that, but you can define some functions in your classes that gives other people the ability to call "iter" on an instance of your class. You can define the function "__iter__" and it must return another object that contains the function "next." It's typical to contain both these functions in the class and simply return itself when "__iter__" is called.

Generators

Python provides a more compact way of creating iterators. A generator is a normal function except it has the keyword "yield" in it. "Yield" is used when you want to return data. Each time next() is called, the function resumes where it left off (from the yield statement). It's basically a function that automatically creates the "__iter__" and "next" functions for you.

>>> def fRange():
for i in range(5):
yield i
>>> for j in fRange():
print j
0
1
2
3
4


In journal #6 I described the cool technique of implicity generating sequences. It's derived from generators, and they are called "generator expressions." This way you don't even have to define a function, you can tell Python to automatically generate a sequence according to some iteration.
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!