Can someone please explain me why the "-1" in this line "max_index = len(words) - 1" | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can someone please explain me why the "-1" in this line "max_index = len(words) - 1"

words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1

3rd Jan 2016, 11:49 PM
Diogo Vilaça
Diogo Vilaça - avatar
2 Answers
+ 2
since there are 4 words Len returns 4 but the individual variables are numbered 0,1,2,3 making the highest variable 3, that's all I could gather
28th Feb 2016, 12:07 AM
Jamaica Nater
Jamaica Nater - avatar
0
exactly, len() built-in returns the size of the object passed as arg. which can lead you to an error if you need the max index of a list, because lists are like arrays and always start at index 0
14th Jul 2016, 3:31 AM
eduardotomassi
eduardotomassi - avatar