Python iterators and Builders

Source: Internet
Author: User

In Python, we often use a for loop to iterate through various collections, such as the most commonly used list,dict and so on, which are iterative objects. Let's take a look at the iterator (Iterator) in Python.

One, iterator

As the name implies, iterators, of course, are used to make iterators (as if they were nonsense). Take list For example, we use list, most of the situation is used to do the loop (loop is the iteration)

>>>List= [1,2,3]>>> dir (List)[' __add__ ',' __class__ ',' __contains__ ',' __delattr__ ',' __delitem__ ',' __delslice__ ',' __doc__ ',' __eq__ ',' __format__ ',' __ge__ ',' __getattribute__ ',' __getitem__ ',' __getslice__ ',' __gt__ ',' __hash__ ',' __iadd__ ',' __imul__ ',' __init__ ',' __iter__ ',' __le__ ',' __len__ ',' __lt__ ',' __mul__ ',' __ne__ ',' __new__ ',' __reduce__ ',' __reduce_ex__ ',' __repr__ ',' __reversed__ ',' __rmul__ ',' __setattr__ ',' __setitem__ ',' __setslice__ ',' __sizeof__ ',' __str__ ',' __subclasshook__ ',' Append ',' Count ',' Extend ',' index ',' Insert ',' Pop ',' Remove ',' Reverse ',' sort ']

List has a __iter__ method. If this method is called, an iterator is returned

>>>it = list.__iter__ ()>>>It<listiterator Object at0x10fa12950>>>>Dir (IT) [' __class__ ',' __delattr__ ',' __doc__ ',' __format__ ',' __getattribute__ ',' __hash__ ',' __init__ ',' __iter__ ',' __length_hint__ ',' __new__ ',' __reduce__ ',' __reduce_ex__ ',' __repr__ ',' __setattr__ ',' __sizeof__ ',' __str__ ',' __subclasshook__ ',' Next ']

A so-called iterator is an object that has the next method. Note that you do not need any parameters when invoking the next method. When the next method is called, the iterator returns its next value. If the iterator does not return a value, the Stopiteration exception is thrown.

>>> it.next()1>>> it.next()2>>> it.next()3>>> it.next()Traceback (most recent call last):  File"<stdin>"1in <module>StopIteration

Some students will ask, we use list with a good, why use what iterator? Because list is a one-time get all values, if the list is large, it takes a lot of memory space, or even large memory load, and the iterator is in the iteration (loop) with a calculation of one, the memory footprint is obviously much smaller.

Implementing Fibonacci sequence with Iterators
#!/usr/bin/env python#coding: Utf-8"' Created on May 6, 2016 @author:lei.wang ' class Fibonacci(object):     def __init__(self):SELF.A =0SELF.B =1     def next(self):self.a,self.b = SELF.B,SELF.A + self.bPrintSelf.areturnSelf.a def __iter__(self):        returnSelfif__name__ = =' __main__ ': fib = Fibonacci () forNinchFib:ifn >Ten:#print N             Break

Just now we're talking about moving from a list to an iterator, can it be a list from an iterator? The answer is of course yes, please see:

#!/usr/bin/env python#coding: Utf-8"' Created on May 6, 2016 @author:lei.wang ' class myiterator(object):index =0     def __init__(self):        Pass     def next(self):Self.index + =1        ifSelf.index >Ten:RaiseStopiterationreturnSelf.index def __iter__(self):        returnSelfif__name__ = =' __main__ ': My_interator = Myiterator () my_list = List (my_interator)PrintMy_list
[12345678910]
Second, generator

When we call a normal Python function (not just the Python function, most of the language's functions are), it is generally done from the first line of the function until the return statement or exception or the last line of the function is encountered. In this way, the function returns control to the caller, all tools in the function, and data such as local variables are lost. When this function is called again, all local variables, stack information will be recreated, with no relation to the previous call.

Sometimes we don't want the function to return only one value, but rather to return a sequence, such as the previous Fibonacci sequence. To do this, this function needs to be able to save its own working state. In this case, you cannot use the return statement that we normally use, because once the return statement is used, the control of the execution of the code is given to the place where the function is called, and all States of the function are zeroed. In this case, we need to use the yield keyword.

Python iterators and Builders

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.