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

乌拉乌拉~
Release: 2018-08-22 16:17:58
Original
8886 people have browsed it

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 >>>
Copy after login

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=" ")
Copy after login

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

1 2 3 4
Copy after login

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()
Copy after login

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

1 2 3 4
Copy after login

The above is all described in this article Content, this article mainly introduces the knowledge related to iteratorinpython. 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 thePython tutorialcolumn 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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!