How to "dereference" an iterator?

Robert Dailey rcdailey at gmail.com
Thu Oct 11 05:24:32 CEST 2007


Hi,

I suppose my question in general is goofy to native python programmers. I'm
originally a C++ programmer and I have a hard time not relating iterators in
python to iterators in STL lol. What I was actually trying to accomplish was
to iterate over 2 iterators using 1 for loop, however I found that the zip()
function allows me to do this quite easily:

list1 = [1,2,3]
list2 = [4,5,6]

for i1,i2 in zip( list1, list2 ):
    # do something here...

In one of my earlier threads in this group someone had ended up using zip().
After reviewing that thread again I found that I could also use it to solve
this problem as well. Sorry for lack of details. Thanks for everyone's help.

On 10/10/07, Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote:
>
> The original post seems to have been eaten, so I'm replying via a reply.
> Sorry for breaking threading.
>
> > 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.
>
> it = iter(mylist)
> while True:
>     print it.next()
>
> but that will eventually end with an exception. Better to let Python
> handle that for you:
>
> it = iter(mylist)
> for current in it:
>     print current
>
> Actually, since mylist is already iterable, you could just do this:
>
> for current in mylist:
>     print current
>
> but you probably know that already.
>
>
> --
> Steven.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071010/70f2995e/attachment.html>


More information about the Python-list mailing list