A brief overview of iterator
Before we say iterator first look at the following code:
for element in iterable
Before we learn for the cycle, in fact, from the iterator element one by one to take.
We note that there are many types of objects can be defined as the iteration in python. Basic container type, such as a list, and a set of tuples, can be defined as an iterative type. In addition, it can also produce a string of characters iteration, iteration dictionary can generate its keys, files can be generated iteration of its lines. User-defined types can also be iterative. In python, iterator mechanism based on the following provisions:
- Iterator is an object that is managed through a series of value iteration. If
i
defined as an iterator object, each call built-in functionsnext(i)
, will have a subsequent sequence from the current element; if there is no subsequent elements, then it will throw anStopIteration
exception. The object
object
is iterative, so by the syntaxiter(object)
can generate an iterator .By these definitions,
list
examples are iterative, but is not itself an iterator . For example,data = [1,3,5,7]
callsnext(data)
are illegal . Only throughi = iter(data)
it can produce an iterator object and then callnext(i)
returns the list of elements. python in thefor
loop syntax is automate this process, creating an iterator is iterable, and then repeatedly call the next element knows captureStopIteration
abnormal.Tip: iterator is usually indirect reference back to the initial element to maintain its status. For example, calls for a list of instances
iter(data)
will have alist_iterator
an instance of the class. Iterator does not store a list of the elements themselves. Instead, he saved the original list of the current index , the index point to the next element. Therefore, if the content in the original list but were modified before the iteration after the completion of construction of the iterator, the iterator will report updates the original list .
# 例子
data = [1,3,5,7]
for i in data:
data.pop()
print(data) #[1,3]