Jump to content
  • Advertisement
Sign in to follow this  
  • entries
  • comments
  • views

Python #9 - Iterators and Generators

Sign in to follow this  



"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()
>>> it.next()
>>> it.next()

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.


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

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  


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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!