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.
- We would get an error for doing math in a range function.
- You are allowed to do math in a range function.
- We would get an error because len(myString)/2 is 1.5 which can't be used in a range.
- Dividing 3 by 2 results in 1.5, which can't be used in a range.
- We would get "M L K" printed with one character per line.
- This would be true if dividing by 2 was truncated to 1.
- We would get "M L K " printed with one character per line plus an extra space at the end.
- This would be true if 1.5 was rounded to 2, but that doesn't happen.
csp-16-8-1: What would happen if we changed line 2 to myList = range(0,len(myString)/2)? (Hint: You could try it)
Discuss topics in this section with classmates.