+ 1

While loops

The first while loop in the tutorial sets the condition : while counter is <= max_index, and sets max_index = len(words) - 1. But after the program runs it still has 4 items in a list of you set it to print(len(words)). What does subtracting 1 do? I’m confused as to what the computer is thinking when it executes this program https://code.sololearn.com/c58L3pPBZ1Ak/?ref=app

11th May 2019, 2:05 PM
PerfectSageMode
PerfectSageMode - avatar
2 Answers
+ 3
The list is changed nowhere, only the items are printed one by one. max-index is set to the length of the list - 1, which is the index of the last item. This value stays the same. In every loop, counter is increased by one and used to print the next element: list[0], list[1], list[2]... ... until counter has become larger than the index of the last element - which means that the whole list has been printed.
11th May 2019, 2:10 PM
HonFu
HonFu - avatar
+ 3
Hi. In addition to HonFu hints, I would like to point out one more thing that often leads to confusion. Python starts indexing lists at '0', while len(some_list) returns the count of elements contained. Since the first element is at index '0', the last element is not at 'element count' but 'element count - 1'. This is why indexes of a list are in range 0 to len(some_list) - 1. Accessing some_list[len(some_list)] will end up in an error. [edit] One more thing you might consider. Since you know up front how often your loop is to be executed, you may also use a for (counted) loop. In this case, python is taking care of handling the counter i.e. for i in range(len(words)): print(words[i]) or even shorter for word in words: print(word) while and do..while loops are usually used when you are unclear up front how often you will have to execute the loop's code. Cheers.C.
11th May 2019, 2:44 PM
ChrA
ChrA - avatar