How to "dereference" an iterator?

Carsten Haese carsten at uniqsys.com
Wed Oct 10 19:40:13 EDT 2007


On Wed, 2007-10-10 at 18:01 -0500, Robert Dailey wrote:
> Hi,
> 
> Suppose I wanted to manually iterate over a container, for example:
> 
> mylist = [1,2,3,4,5,6]
> 
> it = iter(mylist)
> while True:
>     print it
>     it.next()
> 
> In the example above, the print doesn't print the VALUE that the
> iterator currently represents, it prints the iterator itself. How can
> I get the value 'it' represents so I can either modify that value or
> print it? Thanks. 

I have the feeling that you're not telling us the actual problem you're
trying to solve. Python iterators do not, in general, have a notion of a
"current" value. The only have a notion of a next value, which is
returned by next(). If you need to use that value multiple times, you
need to store it somewhere.

If you really must use a while loop, it'll have to look something like
this (add handling of StopIteration to taste):

while True:
    current = it.next()
    print current

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list