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 range and 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.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

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.

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted 1 of 4 activities on this page