How does a Python for loop with iterable work?

amit picture amit · Aug 18, 2009 · Viewed 13k times · Source

What does for party in feed.entry signify and how does this for-loop actually work?

for party in feed.entry:
    print(party.location.address.text)

(I am used to C++ style for-loops, but the Python loops have left me confused.)

Answer

ymv picture ymv · Aug 18, 2009

feed.entry is property of feed and it's value is (if it's not, this code will fail) object implementing iteration protocol (array, for example) and has iter method, which returns iterator object

Iterator has next() method, returning next element or raising exception, so python for loop is actually:

iterator = feed.entry.__iter__()
while True:
    try:
        party = iterator.next()
    except StopIteration:
        # StopIteration exception is raised after last element
        break

    # loop code
    print party.location.address.text