16.2. Iterating Parts of a List¶
Recall that the range
function has a version that looks like: range(start, end, change)
.
It produces a sequence that begins with the start
value, increases by change
at each step,
and stops when it hits end
(but will not include the end
value).
We can use that to do things like iterating through every other item in a list. This program does exactly that by starting from 0 and using a change value of 2. This means it visits indexes 0, 2, 4…
- Change the range to range(0, len(numbers), 3)
- No, that would access indexes 0, 3, 6...
- Change the range to range(1, len(numbers), 2)
- Yes, just by starting at 1, then skipping 2 each time, we'd collect the odds
- Change the range to range(0, len(numbers), 1)
- No, that would access indexes 1, 2, 3...
- Change the range to range(1, len(numbers), 3)
- No, that would access indexes 1, 4, 7...
Which of these changes to the program would give you just the items at odd indexes in a list? (indexes 1, 3, 5… which are for the values 9, 10, 10, 4 in the list above)
Or maybe we want to only iterate through half of the list. We can specify a range that does
not start at 0 and end at len(list_name)
.
The current code loops through just the first half of the list. It calculates half of
the length of the list and uses that as the end
value in the range function call.
If the list length was 5, we would not want to call the halfway point 2.5 There is no
index 2.5 in a list! So when calculating half the length we will use integer division
(//
) to make sure we get a whole number answer.
Modify the code to loop through just the second half of the list.