Instructions for using the Python ITER method

Source: Internet
Author: User

Python 3 about ITER (object[, Sentinel)] The method has two parameters.

This form of use of ITER (object) is more common.

The use of ITER (object, Sentinel) in this form is relatively small, and Python's documentation is seemingly not easy to understand.

Therefore, the use of this function is illustrated here.

1,iter (object)

The official Python documentation is easy to understand for this form of interpretation.

At this point, object must be a collection object and support an iterative protocol (iteration protocol) or a support sequence protocol (sequence protocol).

Plainly, that is, the __iter__ () method or the __getitem__ () method is implemented.

1 lst = [1, 2, 3]2 for in ITER (LST):3     Print (i)

Execution Result:

1
2
3

2,iter (object, Sentinel)

The official Python documentation for this form is interpreted as: "If the second argument, Sentinel, is given, then object must be a callable object . The iterator created in this case would call object with no arguments for each call to its __next__() method; if the VA Lue returned is equal to Sentinel, would be StopIteration raised, otherwise the value would be returned. "

If you pass the second argument, object must be a callable object (for example, a function). At this point, ITER creates an iterator object that is invoked each time the __next__ () method of the iterator object is called.

If the return value of __next__ equals Sentinel, the Stopiteration exception is thrown, otherwise the next value is returned.

1 classCounter:2 3     def __init__(self, _start, _end):4Self.start =_start5Self.end =_end6 7     defGet_next (self):8s =Self.start9         if(Self.start <self.end):TenSelf.start + = 1 One         Else: A             Raisestopiteration -  -         returns the  -  -c = Counter (1, 5) -iterator = iter (C.get_next, 3) + Print(Type (iterator)) -  forIinchiterator: +     Print(i)

Execution Result:

<class ' Callable_iterator ' >
1
2

Instructions for using the Python ITER method

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.