0
Why we write the line -" max_index = len(words) - 1" in the program given bellow?
words=["hello", "world", "spam", "eggs" ] counter =0 max_index=len(words)-1 while counter <= max_index: word=words[counter] counter=counter+1
3 Respostas
+ 3
Because indexing starts from 0 so in words
0 refers to Hello and 3 refers to eggs
And length function counts the number of items like there are 4 in it and returns the value
And obviously there isn't anything at index 4 in words
You could even do
while counter<len(words)
+ 4
Just to make it clear that maximum index in the list is 3
max_index=Len(words)-1 means max_index=3
Much readable than just doing
Counter<Len(words)
0
Why we subtract 1 from "len(words)" ?