What are the iterators in Python? What is the role of iterators?

Source: Internet
Author: User
In the following article, let's look at what is an iterator in Python. Find out What isPython iterators, and what the Python iterator can do 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 remembers where to traverse.

The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

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

A string, list, or tuple object can be used to create an iterator:

>>>list=[1,2,3,4]>>> it = iter (list)    # Create iterator object >>> print (next (it))   # Output iterator next element 1 >>> Print (Next (IT)) 2>>>

An iterator object can be traversed using a regular for statement:

#!/usr/bin/python3 list=[1,2,3,4]it = iter (list)    # Create iterator object for x in it:    print (x, end= "")

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

1 2 3 4

You can also use the next () function:

#!/usr/bin/python3 Import SYS         # introduces the SYS module LIST=[1,2,3,4]IT = iter (list)    # creates an iterator object while True:    try:        print ( Next (IT))    except stopiteration:        sys.exit ()

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

1234

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.