In the context of this code challenge, how can I check if an index is valid?
An index of a list is valid only if that index can be accessed from the list, without causing some error.
Generally, this means that the index must be a whole number, and it must be less than the length of the list, because any index greater than the list length is out of range. In addition, for this exercise, we can assume only positive values being passed in, but to ensure this, we can check that it must be greater than or equal to 0.
Using the above, we can check if an index is valid as the following condition,
if index >= 0 and index < len(list)
This will only work for positive index values, so as a challenge, you can try to implement it so that it accepts valid negative index values, where
-1 is the index for the last element,
-2 is the index for the second to last element, and so on.