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…

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.

You have attempted of activities on this page