Learn more about the use of the Python iter of method

  • 2021-07-16 02:47:53
  • OfStack

Today, we will introduce additional uses of the iter () method learned in the Python basic tutorial. It is said that few people know this usage!

1. Code and learn how to use it

We are all familiar with iter (obj), which will return an iterator. If obj is not an iterable object, an error will be reported. But if you look closely at the official documentation, you will find that the iter () method actually accepts two parameters, which is explained as follows

iter(object[, sentinel])

sentinel translates into Sentinel in English.

The sentinel parameter is optional. When it exists, object no longer passes in an iterative object, but a callable object, which is an object that can be called through () in popular terms, while sentinel acts as a "sentry" like its translation. At that time, when the return value of the callable object is this "sentry", the loop ends and this "sentry" will not be output.

It may be a little difficult to understand. Use a simple requirement to explain it. The requirement description is as follows:

Think about a number in the range of [1, 10], then the code starts to be random, and stops when it reaches the number it wants. Look at how many times the code needs to be random every time.

Implementation analysis: It should look very simple, random, and then add an if judgment, but it is simpler to use iter (). The implementation code is as follows:


from random import randint
def guess():
 return randint(0, 10)
num = 1
#  Here, first write the number that you think is 5
for i in iter(guess, 5):
 print(" No. 1 %s Second guess, the guess number is : %s" % (num, i))
 num += 1
#  When  guess  Returns the  5  An exception is thrown  StopIteration , but  for  The loop handles the exception, that is, it ends the loop 

2. Look at the documentation

About these two parameters, the document is also very detailed, and the segmented explanation is as follows:

The first argument is interpreted very differently depending on the presence of the second argument.

The first parameter has different meanings according to the second parameter

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.

Without the second parameter, object (that is, the first parameter) is a collection object that supports the iterator protocol (which implements the _iter_ () method), or the sequence protocol (which implements the _getitem_ () method) and is indexed from 0. If it does not support any one of them, an TypeError exception is thrown

Simply put, if there is no second parameter, it is a familiar usage. The code example is as follows:


In [5]: iter("123")
Out[5]: <str_iterator at 0x105c9b9e8>
In [6]: iter([1, 2, 3])
Out[6]: <list_iterator at 0x105f9f8d0>
In [7]: iter(123)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-c76acad08c3c> in <module>()
----> 1 iter(123)
TypeError: 'int' object is not iterable

Let's look at the case with the second parameter

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.

If the second parameter sentinel is given, object must be a callable object. This callable object has no parameters. When the return value of the callable object is equal to the value of sentinel, an exception of StopIteration is thrown, otherwise the current value is returned. (If you don't understand callable objects here, you can understand them as functions, which makes it easier to understand.)

For the applicable scenarios of this usage, the document also gives instructions:

One useful application of the second form of iter() is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:

For the second parameter, a useful scenario is to create an blokc-reader, that is, to break the read according to the condition. For example, read a fixed-width block from a binary database file until you reach the end of the file. The code example is as follows:


from functools import partial
with open('mydata.db', 'rb') as f:
 for block in iter(partial(f.read, 64), b''):
 process_block(block)

3. Summary 1

1. The iter () method returns an iterator with or without the second parameter

2. The parameter type of the first parameter of iter () method is determined according to whether there is a second parameter or not


Related articles: