Example of how to use the python iterator

Source: Internet
Author: User
This article mainly introduces how to use the python iterator. the code is very simple. you can refer What is an iterator?

The iterator is a simple object with the next method. of course, the _ iter _ function must be implemented. The iterator can iterate on the values of a series. when there is no iteration available, the next method will cause the StopIteration exception. In python, many objects are called iterators, such as lists, elements, strings, files, mappings, and collections.

How to use the iterator?

1. for variable in iteratable object

The code is as follows:


List1 = [1, 2, 4, 5]

For ele in list1:
Print ele,

Result: 1 2 3 4 5

2. if variable in iteratable object

The code is as follows:


List1 = [1, 2, 4, 5]
Var = 1

If var in list1:
Print 'Yes! '
Else:
Print 'no'

3. variable = iter (iteratable object)

The code is as follows:


It = iter ([1, 2, 4])

Print it. next ()

Print it. next ()

Print it. next ()

Result:

1
2
3

The iterator is an object.

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.