16.8. For Each Item Loop¶
Because it is very common to use a
for loop to touch each of the elements of a collection, we can do it without even using a
index. We can use a
for loop that repeats the body of the loop one time for each value in the collection. This is sometimes called a for each loop since it repeats the body of the loop one time for each element in the collection. It works for both strings and lists as shown below.
This isn’t actually a different
for loop. The function
range actually creates a list of numbers, and the index just steps through each of those items one at a time.
Discuss topics in this section with classmates.