Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Generator Statements

What the for statement really does

In the section called “Iterative Processing: The for Statement”, we defined a for statement using the following summary:

for variable in sequence : suite

This isn't completely accurate, it turns out. We aren't limited to a sequence. The for statement actually requires an iterator or generator. Given an object which is not an iterator or generator, it will call the iter function to get an iterator over the container.

A more correct syntax summary is the the folliowing:

for variable in expression : suite

The Secret of for Once we've looked at generator functions and iterators, we can see what the for statement really does. The purpose of the for statement is to visit each value yielded by a generator, assigning each value to the variable . The for statement examines the expression to see if it is a generator function, or an object. If it is an object, it must respond to the iter function by providing a generator function. All of the built-in collections provide the necessary generator function.

Looking forward, we'll see many additional applications of this feature of the for statement. As we look at designing our own objects in Part III, “Data + Processing = Objects”, we'll want to assure that our objects work well with the for statement, also.


 
 
  Published under the terms of the Open Publication License Design by Interspire