KnowledgeBoat Logo

Computer Science

Assuming words is a valid list of words, the program below tries to print the list in reverse. Does it have an error ? If so, why ? (Hint. There are two problems with the code.)

for i in range(len(words), 0, -1):
    print(words[i], end=' ')  

Python List Manipulation

5 Likes

Answer

There are two issue in range(len(words), 0, -1):

  1. The start index len(words) is invalid for the list words as it will have indexes from 0 to len(words) - 1.
  2. The end index being 0 means that the last element of the list is missed as the list will be iterated till index 1 only.

The corrected python code is :

for i in range(len(words)-1, -1, -1):
    print(words[i], end=' ')

Answered By

2 Likes


Related Questions