0

In this code what is the idea of max_index = len(words) - 1 ? Could someone explain this code step by step please?

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

23rd Nov 2019, 11:51 AM
Esteban Rueda
Esteban Rueda - avatar
2 Réponses
+ 6
words has 4 items, they have the index 0, 1, 2 and 3. So although you have 4 items, the last item is 3 (len - 1) instead of 4. counter starts at zero and is increased by 1 in every run of the loop, but only as long as it's not higher than 3 (max_index). So basically this walks one time through that list. Each word is stored in the variable word and printed out with a ! at the end.
23rd Nov 2019, 11:57 AM
HonFu
HonFu - avatar
+ 1
Thank you very much! @HonFu !
23rd Nov 2019, 1:07 PM
Esteban Rueda
Esteban Rueda - avatar