[Tutor] Tutor Digest, Vol 102, Issue 98
Mark Lawrence
breamoreboy at yahoo.co.uk
Sat Sep 1 10:52:10 CEST 2012
On 01/09/2012 01:20, Steven D'Aprano wrote:
> On 31/08/12 18:31, Mark Lawrence wrote:
>> On 31/08/2012 04:27, William R. Wing (Bill Wing) wrote:
>>>
>>> How about -
>>>
>>>>>> for item in iter(list):
>>>>>> ….print item
>>
>> Overengineering? :) A list is an iterator.
>
>
> Technically, no it isn't, it is an "iterable" or a "sequence" but
> not an iterator.
>
> py> mylist = [1, 2, 3]
> py> next(mylist)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: list object is not an iterator
>
>
>
> You are right to question the call to iter, it is redundant in this
> case, but your terminology is mixed up.
>
> There are three terms normally used to describe things that can
> be used in for-loops:
>
> Sequence
> The generalisation of lists, tuples and strings. Any object that has
> a known length where individual items can be retrieved with the
> __getitem__ method called sequentially: obj[0], obj[1], obj[2], ...
>
> Iterator
> Any object that obeys the "iterator protocol", that is, it must have
> a method __iter__ which returns itself, and a method __next__ which
> returns the iterator items one at a time, then raises StopIteration
> when there are no more items. Examples of iterators include generator
> expressions, generators, the functions from the itertools module,
> and in Python 3, built-ins map, filter and zip.
>
> Iterable
> Any object which can be iterated over, that is, a sequence or
> iterator.
>
>
> The iter() built-in calls the object's __iter__ method. If the object
> is already an iterator, it returns itself unchanged. Since lists are
> not iterators, iter(list) returns a new iterator object:
>
> py> it = iter(mylist)
> py> it
> <list_iterator object at 0xb7caa82c>
> py> iter(it) is it
> True
>
>
>
I thought that when I wrote it, but left it on the grounds that I was
too lazy to look up the correct terminology and I figured you'd soon
correct me :)
--
Cheers.
Mark Lawrence.
More information about the Tutor
mailing list