views:

2211

answers:

6

I am used to the C++ way of for loops, but the Python loops have left me confused.

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

Here party in feed.entry. What does it signify and how does it actually work?

+4  A: 

feed.entry is something that allows iteration, and contains objects of some type. This is roughly similar to c++:

for (feed::iterator party = feed.entry.begin(); party != feed.entry.end(); ++party) {
   cout << (*party).location.address.text;
}
Drakosha
If i remember correctly, it's how old (pre 2.0) python worked (using length(), [] and counter)
ymv
+9  A: 

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
ymv
+1, as giving equivalent lower-level code is often the best explanation; wish I could give only +0.9 since the first line should be `iter(feed.entry)` (most of the time when you're calling a special method directly rather than through a builtin you're doing it wrong, though there are exceptions to this;-).
Alex Martelli
+4  A: 

party simply iterates over the list feed.entry

Take a look at Dive into Python explainations.

Pierre-Jean Coudert
Not necessarily a list. Better to call it an iterable.
Triptych
Yes indeed. But it seemed to be a beginner question. I wanted to keep the response simple.
Pierre-Jean Coudert
+2  A: 

In Python, for bucles aren't like the C/C++ ones, they're most like PHP's foreach. What you do isn't iterate like in a while with "(initialization; condition; increment)", it simply iterates over each element in a list (strings are ITERABLE like lists).

For example:

for number in range(5):
    print number

will output

0
1
2
3
4
willehr
strings are NOT lists. Strings are iterables, and so are lists, but strings and lists are certainly two distinct types in Python.
Triptych
Well, in many languages strings are arrays of characters, and in Python its behavior is very similar when iterating... edit...
willehr
Yes, strings and lists are very similar *when iterating* but importantly different in many other cases. For instance, you cannot modify a string.
Triptych
+1  A: 

To add my 0.05$ to the previous answers you might also want to take a look at the enumerate builtin function

for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
    print i, season

0 Spring
1 Summer
2 Fall
3 Winter
Bartosz Radaczyński
A: 

Python's for loop works with iterators, which must implement the iterator protocol. For more details see:

ars