+ 1
Function
words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 what is the function of '-1' in the above block of code?
3 odpowiedzi
+ 4
Indexes begin at 0, so the max index is always one less than the length of the array.
+ 1
This is a important future in arrays - not only in Python.
Because, len function returns number of items in array. But these are indexed from 0 to number-1.
In this example, number of items in array is 4. But are indexed from 0 to 3. So, this is the reason, for substract 1 from number to get the max_index
+ 1
Thanks Petr and Zen