Python built-in iter functions

Source: Internet
Author: User
This article introduces the Python built-in iter function in detail:

Iter (object [, sentinel])

Return an iterator object. the first argument is interpreted very differently depending on the presence of the second argument. without a second argument, object must be a collection object which supports the iteration protocol (the iter () method), or it must support the sequence protocol (the getitem () method with integer arguments starting at 0 ). if it does not support either of those protocols, TypeError is raised. if the second argument, sentinel, is given, then object must be a callable object. the iterator created in this case will call object with no arguments for each call to its next () method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter () is to read lines of a file until a certain line is reached. the following example reads a file until the readline () method returns an empty string:

with open('mydata.txt') as fp:    for line in iter(fp.readline, ''):        process_line(line)

Note:

1. the function returns an iteratable object.

2. when the second parameter is not provided, the first parameter must be a set (dictionary, set, and immutable set) that supports the iteratable protocol (that is, the iter () method ), alternatively, the sequence protocol (that is, the getitem () method is implemented to receive an integer parameter starting from 0) (tuples, lists, and strings) is supported. Otherwise, an error is returned.

>>> A = iter ({'a': 1, 'B': 2}) # Dictionary set >>>
 
  
>>> Next (a) 'A' >>> next (A) 'B' >>> next (a) Traceback (most recent call last): File"
  
   
", Line 1, in
   
    
Next (a) StopIteration >>> a = iter ('ABC') # string sequence >>>
    
     
>>> Next (a) 'A' >>> next (a) 'B' >>> next (a) 'C' >>>> next () 'D '> next (a) Traceback (most recent call last): File"
     
      
", Line 1, in
      
        Next (a) StopIteration
      
     
    
   
  
 

3. when the second parameter sentinel is provided, the first parameter must be a Callable object. This Callable object is called when the next method is called. when the returned value is the same as the sentinel value, a StopIteration exception is thrown to terminate the iteration.

# Define class >>> class IterTest: def _ init _ (self): self. start = 0 self. end = 10 def get_next_value (self): current = self. start if current <self. end: self. start + = 1 else: raise StopIteration return current >>> iterTest = IterTest () # instantiate class >>> a = iter (iterTest. get_next_value, 4) # iterTest. get_next_value is a Callable object, and the sentinel value is 4 >>>
 
  
>>> Next (a) >>>> next (a) >>> next () # iteration to 4 terminate Traceback (most recent call last): File"
  
   
", Line 1, in
   
    
Next (a) StopIteration
   
  
 

The above is a detailed description of the Python built-in iter function. For more information, see other related articles in the first PHP community!

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.