The difference between iterator and iterable in Python

Source: Internet
Author: User
Tags iterable python list

(Reproduced: http://blog.csdn.net/passionkk/article/details/49929887)

In Python list,truple,str,dict these can be iterated, but they are not iterators. Why?

Because there is a big difference compared to iterators, list/truple/map/dict the size of the data is deterministic, that is to say how many things are known. But the iterator is not, the iterator does not know how many times to execute, so it can be understood to not know how many elements, each call to next (), will go down a step, is inert.

Judging whether it is possible to iterate, with iterable


From collections import iterable

Isinstance ({}, Iterable)-- True

Isinstance ((), iterable)-- True

Isinstance (iterable)--- False

Judging is not an iterator, with iterator


From collections import Iterator

Isinstance ({}, Iterator)--- False

Isinstance ((), Iterator)--- False

Isinstance ((x for x in range), Iterator)- --True


So

Anything that can be used for a loop is iterable.

Anything that can next () is iterator.

The collection data type, such as LIST,TRUPLE,DICT,STR, is itrable not iterator, but a iterator object can be obtained through the ITER () function

The For loop in Python is implemented through next

The difference between iterator and iterable in Python

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.