How to detect the last element in a for loop

Fredrik Lundh fredrik at pythonware.com
Sat Jul 27 18:02:52 EDT 2002


Tom Verbeure wrote:

> I am not familiar with iterators as objects in Python. I understand that
>
>     for a in myList:
>         ...
>
> will result in an implicit iterator on myList. How would you create an
> explicit iterator object of myList?

the built-in iter() function will do this for you:

>>> L = [1, 2, 3, 4, 5]
>>> I = iter(L)
>>> L
[1, 2, 3, 4, 5]
>>> I
<iterator object at 0x007D9728>
>>> I.next()
1
>>> for i in I:
...     print i
...
2
3
4
5
>>> I.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

</F>





More information about the Python-list mailing list