Understanding Python's Iterators

Source: Internet
Author: User

What is an iteration

An object that can directly act on a for loop is called an iterative object (iterable).
An object that can be called by the next () function and continually returns the next value is called an iterator (Iterator).
All iterable can be converted to iterator via the built-in function iter ().

For iterators, one __next__ () is enough. When you use the for and in statements, the program automatically invokes the iterator object of the object being processed, and then uses its __next__ () method until a Stopiteration exception is detected.

>>> L = [n/A]
>>> [x**2 for x in L]
[1, 4, 9]
>>> Next (L)
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' List ' object is a iterator
>>> I=iter (L)
>>> Next (I)
1
>>> Next (I)
2
>>> Next (I)
3
>>> Next (I)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Stopiteration

In the example above, the list L can be looped by for but cannot be used by the built-in function next () to find the next value, so L is iterable.
L is set to i,i via ITER and can be used by next () to find the next value, so I is iterator.

Off Topic:

Built-in functions iter () is simply the __iter__ () method that invokes the object, so there must be a method inside the list Object __iter__ ()

The built-in function next () simply calls the __next__ () method of the object, so there must be no method __next__ () Inside the list object, but this method must exist in the Itrator.

The inside of the For loop is actually the first call to ITER () to turn the iterable into iterator in the loop iteration.

>>> L = [4,5,6]
>>> I = l.__iter__ ()
>>> l.__next__ ()
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror: ' List ' object has no attribute ' __next__ '
>>> i.__next__ ()
4
>>> from collections import Iterator, iterable
>>> isinstance (L, iterable)
True
>>> isinstance (L, Iterator)
False
>>> isinstance (I, iterable)
True
>>> isinstance (I, Iterator)
True
>>> [x**2 for x in I]
[25, 36]

Iterator inherits from Iterable, it is easy to see iterator contains __iter__ () and __next__ () methods from the following tests, and iteratble only contains __iter__ ().

>>> from collections import Iterator, iterable
>>> Help (Iterator)
Help on class Iterator:

Class Iterator (iterable)
| Method Resolution Order:
| Iterator
| Iterable
| Builtins.object
|** Note: From here can be seen iterable inherit from object, iterator inherit from Iterable.
| Methods defined here:
|
| __iter__ (self)
|
| __next__ (self)
| Return the next item from the iterator. When exhausted, raise stopiteration
......
>>> Help (Iterable)
Help on class Iterable:

Class Iterable (Builtins.object)
| Methods defined here:
|
| __iter__ (self)
......

Iterable needs to include a __iter__ () method to return iterator, and iterator needs to include a __next__ () method to be looped

If we define an iterator ourselves, as long as we define a __iter__ () function within the class, it is enough to return an object with the __next__ () method.
Directly on the code

Class Iterable:
def __iter__ (self):
Return Iterator ()

Class Iterator:
def __init__ (self):
Self.start=-1
def __next__ (self):
Self.start +=2
If Self.start >10:
Raise Stopiteration
Return Self.start

I = Iterable ()
For I in I:print (i)

The above code implementation is to find the odd number within 10, the code of the class name can be arbitrarily taken, not necessarily need to use the class name I provided above.
If the stopiteration exception is not implemented in the __next__ method of iterator, then it is all the odd number represented, then the condition of exiting the loop needs to be set at the time of the call.

Class Iterable:
def __iter__ (self):
Return Iterator ()

Class Iterator:
def __init__ (self):
Self.start=-1
def __next__ (self):
Self.start +=2
Return Self.start

I = Iterable ()
For count, I in Zip (range (5), I): #也可以用内置函数enumerate来实现计数工作.
Print (i)

We use range to print how many elements, here is to print 5 elements, return the result and the same as above.

Of course, we can combine the two classes together to make the program concise.
The final version is as follows

Class Iterable:
def __iter__ (self):
return self
def __init__ (self):
Self.start=-1
def __next__ (self):
Self.start +=2
If Self.start >10:
Raise Stopiteration
Return Self.start

I = Iterable ()
For I in I:
Print (i)

Copy iterators

Iterators are disposable consumables and are empty after use, please see.

>>> l=[1,2,3]
>>> I=iter (L)
>>> for i in I:
... print (i, end= '-')
...
1-2-3-
>>>next (I)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Stopiteration

When the loop is exhausted, the stopiteration exception is thrown when the call is used again.

We want to save the iterator in the form of a direct assignment, which we can use next time.
But as you can see from the example below, it doesn't work at all.

>>> I=iter (L)
>>> j=i
>>> Next (I)
1
>>> Next (J)
2
>>> Next (I)
3
>>> Next (J)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Stopiteration

So how can we achieve the effect we want?
We need to use the deepcopy in the copy package, see below:

>>> Import Copy
>>> I=iter (L)
>>> j=copy.deepcopy (I)
>>> Next (I)
1
>>> Next (I)
2
>>> Next (J)
1

Add: iterators cannot be moved backwards and cannot go back to the beginning.
So some special things need to be done in order to realize the function of backward moving.

The above code is tested in Python 3.4.

The above is the understanding of Python iterator content, more related articles please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.