How can I check if an index is valid?


#1

Question

In the context of this code challenge, how can I check if an index is valid?

Answer

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.


#2

In Python we can write inequality expressions with relations on both sides of the variable.

if 0 <= x < len(lst)

This removes the need for a logical operation.

All the valid indices are between negative list length, inclusive and list length, exclusive.

if -len(lst) <= x < len(lst)

and can be found in the list generated on that range.

if x in range(-len(lst), len(lst))
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = 9
>>> x in range(-len(lst), len(lst))
False
>>> x = -9
>>> x in range(-len(lst), len(lst))
True
>>>