+ 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?

19th Oct 2016, 9:53 AM
Michael Suleiman
Michael Suleiman - avatar
3 odpowiedzi
+ 4
Indexes begin at 0, so the max index is always one less than the length of the array.
19th Oct 2016, 10:50 AM
Zen
Zen - avatar
+ 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
19th Oct 2016, 10:44 AM
Petr Hatina
Petr Hatina - avatar
+ 1
Thanks Petr and Zen
19th Oct 2016, 2:21 PM
Michael Suleiman
Michael Suleiman - avatar