Python next function

Time:2020-10-25

The python 3. X built-in function next can retrieve the next element or data from the iterator, and can be used for iterator traversal. When using it, please note that the stopiteration exception will be triggered!

 

1、 Introduction to next function

The grammar is as follows:

next(iterator[,default])

 

 

Iterator – iterator;

Default – optional parameter;If it is not set, stopiteration exception will be thrown when there is no next element in the iterator. If this parameter is set and there is no next element, the parameter will be returned by default;

Return value: returns the next element of the current element in the iterator;

 

2、 Next function

1. The default parameter is not set. When using the next function, if there is no next element or data, the stopiteration exception will be thrown. Pay attention to exception handling;

 

>>> a = iter('1234')
>>> next(a)
'1'
>>> next(a)
'2'
>>> next(a)
'3'
>>> next(a)
'4'
>>>Next (a) ා use next when there is no next element, and throw the exception stopiteration directly
Traceback (most recent call last):
 File "", line 1, in 
  next(a)
StopIteration

 

 

2. Use the default parameter and the next function. If there is no next element or data, return the default value;

>>> a = iter('1234')
>>> next(a,'e')
'1'
>>> next(a,'e')
'2'
>>> next(a,'e')
'3'
>>> next(a,'e')
'4'
>>>Next (a, 'e')? When there is no next element, use next to return the default parameter directly
'e'
>>> next(a,'e')
'e'

 

 

 

 

Guess you like it:

1. Python thread creating threading

2. Python thread mutex lock

3. Python thread event

4. Python Gil lock

 

Please note: Python next function

 

Please contact the blogger directly for technical exchange and business cooperation
Scan code or search: ape says Python
python教程公众号
Python
WeChat official account swept the attention