How to "dereference" an iterator?

Steven D'Aprano steve at
Thu Oct 11 04:46:09 CEST 2007

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
>> 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:

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.


More information about the Python-list mailing list