Help on for loop understanding

Erik python at lucidity.plus.com
Mon Dec 7 20:53:34 EST 2015


Hi Robert,

On 08/12/15 01:39, Robert wrote:
>> I don't find a way to show __next__ yet.
>> Can we explicitly get the iterator for a list?
>> Thanks,
>
> Excuse me. I find it as the following:
>
> xx.__iter__().next
> Out[16]: <method-wrapper 'next' of listiterator object at 0x0000000008B38AC8>
>
> xx.__iter__().next()
> Out[17]: 1

Robin has told you how things work under the hood for the particular 
version of Python that he is running (Python 3). As you've seen, it 
works a bit different under the hood in your version (Python 2).

This is why you should not be calling the __ ("dunder") methods 
directly. Until you understand more and want to write your own classes 
that support being iterated using the 'for' keyword, you should probably 
ignore them.

Instead, the way to do this which works on all versions is:

x = [1, 2, 3, 4]

xit = iter(x)
next(xit)
next(xit)
next(xit)
next(xit)
next(xit)

This is what the 'for' keyword is doing for you - it first gets an 
iterator for the list (using iter()) and then processes each element 
that the iterator returns (from next()) until it raises the exception. 
It then suppresses the exception (so you don't have to catch it 
yourself) and exits the for loop.

Of course, it might actually do this using the __ methods and other 
things as a shortcut internally, but that's just an implementation detail.

E.



More information about the Python-list mailing list