Home  >  Article  >  Backend Development  >  What is an iterator in python? What is the role of iterator?

What is an iterator in python? What is the role of iterator?

乌拉乌拉~
乌拉乌拉~Original
2018-08-22 16:17:588960browse

In the following article, we will learn about what is an iterator in python. Learn aboutwhat ispythoniterator, and what role python iterators can play in python programming.

What is a python iterator

Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.

An iterator is an object that can remember the position of the traversal.

The iterator object starts accessing from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward.

Iterators have two basic methods: iter() and next().

String, list or tuple objects can be used to create iterators:

>>>list=[1,2,3,4]
>>> it = iter(list)    # 创建迭代器对象
>>> print (next(it))   # 输出迭代器的下一个元素
1
>>> print (next(it))
2
>>>

Iterator objects can be traversed using regular for statements:

#!/usr/bin/python3
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
for x in it:
    print (x, end=" ")

Execute the above program, The output result is as follows:

1 2 3 4

You can also use the next() function:

#!/usr/bin/python3
 
import sys         # 引入 sys 模块
 
list=[1,2,3,4]
it = iter(list)    # 创建迭代器对象
 
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

Execute the above program, the output result is as follows:

1
2
3
4

The above is all described in this article Content, this article mainly introduces the knowledge related to iterator in python. I hope you can use the information to understand the above content. I hope what I have described in this article will be helpful to you and make it easier for you to learn python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What is an iterator in python? What is the role of iterator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn