Python iterator and python Generator

Source: Internet
Author: User

Python iterator and python Generator
The objects that can directly act on the for loop are called iterable objects. The objects that can be called by the next () function and continuously return the next value are called iterator ); all iteratable objects can be converted to iterators through the built-in function iter. When the for loop is used, the program automatically calls the iterator object of the object to be processed, and then uses its next () method until it detects a stoplteration exception.

>>> L = [, 0] # This is a list
>>> I = iter (l) # The iteratable object is converted into an iterator;
>>> Next (I)
4
>>> Next (I)
5
>>> Next (I)
6
>>> Next (I)
7
>>> Next (I)
8
>>> Next (I)
9
>>> Next (I)
0
>>> Next (I)
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
StopIteration

Because the number in the list exceeds 0, a StopIteration exception is returned if the range is exceeded.

How can we determine in the production environment?

>>> L = [4, 5, 6]
>>> I = L. _ iter __()
>>> L. _ next __()
Traceback (most recent call last ):
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]

 

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.