Main.Iterators History

Hide minor edits - Show changes to markup

February 21, 2010, at 07:40 PM MST by 71.196.160.210 -
Added lines 1-34:

(:source lang=python:)

""" Iterators in python """

  1. Many kinds of python objects can be iterated over using the for loop:
  2. lists

for element in [1, 2, 3]:

    print element
  1. strings

for char in "123":

    print char
  1. files

for line in open("myfile.txt"):

    print line
  1. Behind the scenes, the for statement calls iter() on the object.
  2. this returns an iterator object - an object that has a next() method
  3. which returns the next element in the sequence of elements.
  4. When there are no more elements, next() raises a StopIteration exception
  5. which tells the for loop to terminate.

s = 'abc' it = iter(s) it.next() it.next() it.next()

  1. the next one will raise an exception:

it.next()

(:sourceend:)