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?
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?
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;
}
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
party simply iterates over the list feed.entry
Take a look at Dive into Python explainations.
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
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
Python's for
loop works with iterators
, which must implement the iterator
protocol. For more details see: