What does it mean to “consume” in Python? In an iterator?

前端 未结 6 749
既然无缘
既然无缘 2020-12-11 01:45

I have been working in Python for a few months now, and it has occurred to me that I often overlook vocabulary that escapes me at first glance, instead trying to get the gis

6条回答
  •  渐次进展
    2020-12-11 02:20

    Iterators are just objects that support the methods __iter__ and next. The general use case for iterators is to loop over them, where each time through the loop the result of iterator.next() will be assigned to a variable.

    With this in mind, a call to iterator.next() could be referred to as "consuming a value" because in general a call to next changes the state of the iterator, and there is no way to return to that previous state.

    However, there is nothing preventing an iterator from returning the same value repeatedly, or even providing a way to roll back to a previous state. In those cases using the word "consume" may not be as applicable.

    As far as what happens to the data that is returned by the iterator's next method, it is completely dependent on the implementation of the iterator. Generators tend to discard the results that they yield, but if a container is also an iterator then the data returned when next() is called will still exist in the container object.

提交回复
热议问题