Help on for loop understanding

Robert rxjwg98 at gmail.com
Mon Dec 7 20:05:55 EST 2015


Hi,
When I learn for loop with below link:

http://www.shutupandship.com/2012/01/understanding-python-iterables-and.html

it has such explanation:

\\\\\\\\\
for loop under the hood

First let's look at the for loop under the hood. When Python executes the
 for loop, it first invokes the __iter__() method of the container to get the
 iterator of the container. It then repeatedly calls the next() method
 (__next__() method in Python 3.x) of the iterator until the iterator raises a
 StopIteration exception. Once the exception is raised, the for loop ends.
\\\\\\\\\

When I follow a list example from the above link, and one example of myself:

//////////
xx=[1,2,3,4,5]

xx.next
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-76-dd0716c641b1> in <module>()
----> 1 xx.next

AttributeError: 'list' object has no attribute 'next' 

xx.__iter__
Out[77]: <method-wrapper '__iter__' of list object at 0x000000000A1ACE08>

for c in xx: print c
1
2
3
4
5
//////////////

I am puzzled that the list examples have no next method, but it can run as
a for loop. Could you explain it to me the difference?

Thanks,



More information about the Python-list mailing list