0
What is the minus 1 in line 3 actually doing in this loop? âmax_index = len(words) - 1â.
1. words = ["hello", "world", "spam", "eggs"] 2. counter = 0 3. max_index = len(words) - 1 4. while counter <= max_index: 5. word = words[counter] 6. print(word + "!") 7. counter = counter + 1
1 Answer
+ 8
Words has 4 items in the list. A list uses a zero based index so the 1st item is at index 0 and in this case the last item is at index 3. len(words) will return a length of 4. The length of a list minus 1 will give you the integer for the last index in a list. In this case 3. This insures that you don't attempt to access an item via an index that is beyond the end of the list.