Python Practical note (11) Advanced Features--iterators

Source: Internet
Author: User
Tags iterable

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object:

>>> from collections import Iterable>>> isinstance([], Iterable)True>>> isinstance({}, Iterable)True>>> isinstance(‘abc‘, Iterable)True>>> isinstance((x for x in range(10)), Iterable)True>>> isinstance(100, Iterable)False

An object that can be called by next() a function and continually returns the next value is called an iterator: Iterator .

You can use to isinstance() determine whether an object is an Iterator object:

>>> from collections import Iterator>>> isinstance((x for x in range(10)), Iterator)True>>> isinstance([], Iterator)False>>> isinstance({}, Iterator)False>>> isinstance(‘abc‘, Iterator)False

Generators are Iterator objects, but,, list dict str Though Iterable they are, they are not Iterator .

Turn list , dict and str wait for the Iterable Iterator function to be used iter() :

>>> isinstance(iter([]), Iterator)True>>> isinstance(iter(‘abc‘), Iterator)True

You may ask, why, list dict , str etc. data types are not Iterator ?

This is because the Python Iterator object represents a data stream, and the iterator object can be next() called by the function and will return the next data continuously until there is no data to throw an StopIteration error. You can think of this data stream as an ordered sequence, but we can't know the length of the sequence in advance, only by continuously using the next() function to calculate the next data on demand, so Iterator the calculation is lazy, and it will only be calculated when the next data needs to be returned.

IteratorIt can even represent an infinitely large stream of data, such as the whole natural number. Using list is never possible to store all natural numbers.

Python Practical note (11) Advanced Features--iterators

Related Article

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.