How does a Python for loop with iterable work?

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

Leave a Comment