[Tutor] iteritems() for a list

Abel Daniel abli@freemail.hu
Sun Jun 29 18:59:02 2003


Tim Johnson wrote:
> Hello All:
> I use an object that has a list as a major component.
> 
> I would like to iterate through that list
> 2 items at a time like dict.iteritems().

You mean something like this? :

>>> l=range(5)
>>> l
[0, 1, 2, 3, 4]
>>> ll=zip(l, l[1:])
>>> ll
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> for i,j in ll:
...  print i,j
... 
0 1
1 2
2 3
3 4
>>> 

For large lists, this won't be really good, as we copy the list, so it
will use much more memory then really needed. (This won't be an issue
for short lists.)

> 
> I believe that python2+ provides for custom
> iterators.
>     
> If I'm correct:
> Could someone point me to some code examples
> to help me get started on this?
It's called generators, and it was introduced in 2.2 . As it uses a new
keyword, it isn't enabled by default in 2.2, only in 2.3. In 2.2 you
have to do
from __future__ import generators
before using one.

There is a short description about how they work and how to use them at:
http://www.python.org/doc/2.2.2/whatsnew/node5.html

The task you mentioned can be done with generators in a 'lazy way' so
that memory usage is kept to a minimum. As you asked for code examples,
and not finished code, I won't paste the solution here... :)
I think that link describes everything you need. If you have questions,
feel free to ask.

Abel Daniel