How can I check if an index is valid?

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.

6 Likes

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
>>> 
2 Likes

Since an invalid index raises an error, i used try/except to solve this problem :slight_smile:

Hi, I now know how the exercice is supposed to be done, but I wanted to make sure my solution was also viable. Here’s how I did it :

def double_index(lst, index):
  try:
    lst[index] = lst[index] * 2
  except IndexError:
    return lst

Seems like it works on my side, and is easier/cleaner. Is there something else I am missing that makes this a bad solution?

4 Likes

That is a perfectly viable solution, so long as we understand the other methods of validating the inputs. The objective for a beginner is to learn all the possible solutions, not just the simplest or best. Often we get blinded to other approaches when we get hung up on superlatives.

3 Likes

Thank you for the quick answer, that is a fair point. I wouldn’t have thought immediatly about the method expected by the exercice, so I’m glad I learned two different ways of doing it.

1 Like

Hi I’m was also stucked in the challenge. I solved it but checking the solution I saw that the comand return the list. So no metter what you do, it aways return the list instead the index double.
How can it be right if the response for the challenge is -20?

So I changed the code to:
def double_index(lst, index):
if index < len(lst):
lst[index] = lst[index] * 2

And it worked well, but it I insert a number out of the range it return an erro (I was hope because I didn’t use nothing to deal with it). So I use the “else” to return the list if index
def double_index(lst, index):
if index < len(lst):
lst[index] = lst[index] * 2
else:
lst[index] = lst

return lst[index]

If the index is in the range the code runs right. However if the index is out of the range it returns an error

My logic is right? To built the code this way?
What Am I missing with the “else”?

Thanks

Consider that in all cases you will return the list.

def double_index(lst, index):
    # code
    return lst

Now insert just the if statement and action for the # code with no else.

Thanks for your help.

1 Like

It’s unfair.as a beginner,I just spent a lot of time to find a method all by the contents Codecademy taught me before.I thought there would be a better solution than IF statement,because this Pro course have not mentioned it. I thought I could believe Codecademy,but it’s proved to be wrong.

Hello friends,

I’ve just revised this exercise again and reading the comments posted (thanks to op and mtf) helped me find 2 more ways to go about it. I hope my addition will help those who are new and still confused about this.

# Valid for positive indexes only
def double_index(lst, index):
  if index >= 0 and index < len(lst):
    lst[index] = lst[index] * 2
  return lst

print(double_index([3, 8, -10, 12], 2))
#prints [3, 8, -20, 12]
print(double_index([3, 8, -10, 12], -1)) 
#prints [3, 8, -10, 12]  << this is the original list, as a negative index such as -1 is viewed as invalid, the original list is return by the function

---

# Method 1 - Valid for both positive & negative indexes
def double_index(lst, index):
  if -len(lst) <= index < len(lst):
    lst[index] = lst[index] * 2
  return lst

print(double_index([3, 8, -10, 12], 2))
#prints [3, 8, -20, 12]
print(double_index([3, 8, -10, 12], -1)) 
#prints [3, 8, -10, 24]

#Method 2 - Valid for both positive & negative indexes
def double_index(lst, index):
  if index in range(-len(lst), len(lst)):
    lst[index] = lst[index] * 2
  return lst

print(double_index([3, 8, -10, 12], 2))
#prints [3, 8, -20, 12]
print(double_index([3, 8, -10, 12], -1)) 
#prints [3, 8, -10, 24]

1 Like