What is the minus 1 in line 3 actually doing in this loop? “max_index = len(words) - 1“. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

11th Nov 2017, 1:20 AM
Divus iulius
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.
11th Nov 2017, 1:29 AM
ChaoticDawg
ChaoticDawg - avatar