Lesson 6
Dealing with Sequences of Objects
Chapter 4: for loops
for loops
So far, we have mainly used while loops.
Python also provides what is called a for loop.
for loops are useful for iterating over a collection of object, like a list.
The code below is self explanatory and should even read like English.
words = ["I", "have", "a", "dream"]
for word in words:
print(word)
Note that the in operator here is different from what we have discussed earlier (as a list membership operator).
In a for loop, in assigns each element to a variable at each step. In the above example, word is assigned to "I" in the first iteration, word="have" in the second iteration, and so on.