An iterator is an object i such that you can call i.next() with no arguments. i.next() returns the next item of iterator i or, when iterator i has no more items, raises a StopIteration exception. When you write a class (see "Classes and Instances" on page 82), you can allow instances of the class to be iterators by defining such a method next. Most iterators are built by implicit or explicit calls to built-in function iter, covered in iter on page 163. Calling a generator also returns an iterator, as we'll discuss in "Generators" on page 78. The for statement implicitly calls iter to get an iterator. The following statement: for x in c: is exactly equivalent to: _temporary_iterator = iter(c) where _temporary_iterator is some arbitrary name that is not used elsewhere in the current scope. Thus, if iter(c) returns an iterator i such that Many of the best ways to build and manipulate iterators are found in standard library module itertools, covered in "The itertools Module" on page 183. range and xrange Looping over a sequence of integers is a common task, so Python provides built-in functions range and xrange to generate and return integer sequences. The simplest way to loop n times in Python is: for i in xrange(n): range(x) returns a list whose items are consecutive integers from 0 (included) up to x (excluded). While range returns a normal list object, usable for all purposes, xrange returns a special-purpose object, specifically intended for use in iterations like the for statement shown previously (unfortunately, to keep backward compatibility with old versions of Python, xrange does not return an iterator, as would be natural in today's Python; however, you can easily obtain such an iterator, if you need one, by calling iter(xrange(...))). The special-purpose object xrange returns consumes less memory (for wide ranges, much less memory) than the list object range returns, but the overhead of looping on the special-purpose object is slightly higher than that of looping on a list. Apart from performance and memory consumption issues, you can use range wherever you could use xrange, but not vice versa. For example: >>> print range(1, 5) Here, range returns a perfectly ordinary list, which displays quite normally, but xrange returns a special-purpose object, which displays in its own special way. Please check back next week for the continuation of this article.
blog comments powered by Disqus |