What exactly are iterator, iterable, and iteration?

前端 未结 13 1669
遥遥无期
遥遥无期 2020-11-21 05:27

What is the most basic definition of \"iterable\", \"iterator\" and \"iteration\" in Python?

I have read multiple definitions but I am unable to identify the exact m

13条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 06:04

    Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.

    In Python, iterable and iterator have specific meanings.

    An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.

    An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

    Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.

    A good place to start learning would be the iterators section of the tutorial and the iterator types section of the standard types page. After you understand the basics, try the iterators section of the Functional Programming HOWTO.

提交回复
热议问题