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

22nd May 2020, 3:56 PM
Kshirod Panigrahi
3 Respuestas
+ 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)
22nd May 2020, 4:00 PM
Abhay
Abhay - avatar
+ 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)
22nd May 2020, 4:08 PM
Abhay
Abhay - avatar
0
Why we subtract 1 from "len(words)" ?
22nd May 2020, 4:05 PM
Kshirod Panigrahi