A brief overview of iterator

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 idefined as an iterator object, each call built-in functions next(i), will have a subsequent sequence from the current element; if there is no subsequent elements, then it will throw an StopIterationexception.
  • The object objectis iterative, so by the syntax iter(object)can generate an iterator .

    By these definitions, listexamples are iterative, but is not itself an iterator . For example, data = [1,3,5,7]calls next(data)are illegal . Only through i = iter(data)it can produce an iterator object and then call next(i)returns the list of elements. python in the forloop syntax is automate this process, creating an iterator is iterable, and then repeatedly call the next element knows capture StopIterationabnormal.

    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 a list_iteratoran 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]

Guess you like

Origin www.cnblogs.com/Du704/p/11352128.html