Last Updated on 2021-09-20 by Clay
Recently, when I reading the source code of a Python project, I saw they used next()
function to take the iterator elements. At first I didn't know how to use the function, so I decided to study the use and record it.
The following is simple record of the purpose of the next()
function and the iter()
function that is often used together.
How to use next() function
The next()
function returns the next element of the "iterator", so if we have many elements stored in a List or Tuple and want to use the next() function to read out, we need to use the iter()
function to convert it into an iterator.
# coding: utf-8 def main(): data = [1, 2, 3, 4, 5] data = iter(data) print(next(data)) print(next(data)) print(next(data)) if __name__ == '__main__': main()
Output:
1
2
3
As you can see, next()
function will read out the elements.
If we set a specified parameter for next()
, it will become the default null element.
# coding: utf-8 def main(): data = [1, 2, 3, 4, 5] data = iter(data) for _ in range(10): print(next(data, 777)) if __name__ == '__main__': main()
Output:
1
2
3
4
5
777
777
777
777
777
Just like the above program. If the default value is not specified and an empty object is read, an error message StopIteration will be thrown.
References
- https://www.programiz.com/python-programming/methods/built-in/next
- https://www.w3schools.com/python/ref_func_next.asp
- https://www.geeksforgeeks.org/python-next-method/