The for Statement

The for statement repeatedly executes a suite of statements as it iterates through the items in a sequence. It appears as

for item in sequence :
       suite

The expression should be a valid sequence (a tuple, string, or list). At the beginning of each iteration, the next item in the sequence is assigned to the item variable, and the suite is executed. This continues until all items have been dealt with.

To illustrate for, let's say that we have a list of email addresses for a monthly newsletter.

 >>> email_list = ["rick_m_hightower@emailcompany.com", "adam_s_carr@hottermail.com", "bill_g_smith@hottestmail.com"] >>> >>> for address in email_list: ... print ("Sending email to " + address) ... # sendEmail(address, "Nothing new here") ...

Get Python Programming with the Java™ Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.