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



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to