Iterators in Python

Source: Internet
Author: User

Iterator (iterator) protocol

· In Python, the support iterator protocol is the __iter__ () and __next__ () methods that implement the object.

1. __iter__ () Method: Returns the Iterator object itself;

2. __next__ () Method: Returns the next element in the container and throws an stoplteration abort iterator at the end.

an Iterative object (iterable)

· An object that implements an iterator protocol is an iterative object.

· How to implement an iterator protocol: an __iter__ () method is defined within an object.

· In Python, the string, tuple, list, dict, set, and file are all iterative objects. In short, you can call out the __iter__ () method with the Python built-in function, which is an iterative object.

As follows:

    1. # str1= ' Hello '
    2. # list1=[1,2,3]
    3. # tup1= (a)
    4. # dic={' x ': 1}
    5. # s1={' A ', ' B ', ' C '}
    6. # f=open (' A.txt ', ' W ', encoding= ' utf-8 ')

Can be debugged with __iter__ ().

Iterator Object

· Iterator object:

Refers to objects that have both built-in __iter__ methods and built-in __next__ methods. Only files are iterator objects
As follows:
    1. # f=open (' db.txt ', ' RT ', encoding= ' utf-8 ')
    2. # Print (f.__next__ ())
    3. # Print (f.__next__ ())
    4. # print (Next (f))
Disadvantages of Iterators
1. The value of the iterator is not as flexible as the index, because it can only be taken back.
2. Cannot predict the number of iterator values
As follows:
    1. name=[' Egon ', ' alex_sb ', ' WXX_SB ']
    2. RES=NAME.__ITER__ ()
    3. Print (res.__next__ ())
    4. Print (Name[0])

Iterator benefits

  • For data structures that support random access: list, tuple, and so on, the iterator has no advantage over the classic for loop (indexed access), but loses the index value. However, you can use the built-in function to enumerate() retrieve this index value. But for data structures that cannot be accessed randomly: set() iterators are the only way to access elements.
  • Save Memory: iterators do not need to prepare all the elements of the entire iteration in advance, only the element is evaluated when iterating to an element, and the element may not exist or be destroyed before or after that. This is also one of the great advantages of iterators: It is suitable for traversing a large or infinite set, such as a file of several G. Let's take the Fibonacci sequence as an example:
    • The code, which is printed directly in fab(max) print, causes the reusability of the function to become worse, so Fab returns none. Other functions cannot get the sequence returned by the FAB function;
    • Code two satisfies the requirement of reusability, but occupies the memory space;
    • Code three Fabs class throughnext()Continuously returns the next number of columns, and memory consumption is always constant.
      #代码一:DefHa(max): L = [] n, a, B =0,0,1While n < Max:l.append (b) A, B = B, A + b N = n +1Return L#代码二:DefFab(max): N, a, B =0,0,1While n < max:Print B A, B = B, A + b N = n +1#代码三:Classfab (object):  def __init__ (self, max): Self.max = Max SELF.N, self.a, self.b = Span class= "Hljs-number" >0, 0, 1 < Span class= "Hljs-keyword" >def __iter__ (self): return self def  Nextif self.n < Self.max:r = Self.b self.a, self.b = sel f.b, SELF.A + self.b SELF.N = SELF.N + 1 return R raise stopiteration ()            

Iterators in Python

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.