# 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?

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.

12 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
>>>
``````
8 Likes

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

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?

10 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.

5 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]

``````
8 Likes

I’m using this code, but it keeps saying that I didn’t defined what to do if “index is too big”

def double_index (lst, index):
new_index = lst[index]*2
lst_len = len(lst)

if index > lst_len:
return lst
else:
return lst.append(new_index)

2 Likes

`if index > lst_len` will still allow for one index higher than the list itself contains; remember, they’re zero-indexed! Replacing > with >= should solve that issue.

2 Likes

Hello coders,

I have tried many solutions on this exercise…my brain is a bit fried right now…this was my last solution and I keep getting the Codecademy message at the bottom “Make sure to define what should happen if INDEX is too big.” I cannot get around this message and I really would like to solve this function without getting solution…any help would be greatly appreciated:)

def double_index(lst, index):
new_list = lst[index] * 2
if index < len(lst):
return new_list
elif index > len(lst):
return lst

print(double_index([3, 8, -10, 12], 2))

The general approach is to the validating before attempting to run code on the object. If we run the code first, we may hit upon an `index out of range` exception before the validation line is reached.

``````if len(lst) >= index:
lst[index] *= 2
return lst
``````

In both cases the list is returned, but is only modified when the index is valid.

From what I recall, early on in the unit on lists we are shown that lists are mutable, meaning we can change the values, add new elements and remove elements.

The function should double the value of the element at `index` of `lst` and return the new list with the doubled value.

If `index` is not a valid index, the function should return the original list.

I took the last instruction to mean don’t do anything to the list, just return it. There is no expected message, just the original list.

``````if index is valid (that is, within range)
then change the element at that index
else do nothing
in both cases return the list.``````
2 Likes

Hey,

I can’t understand the solution suggested:

def double_index(lst, index):
if index >= len(lst):
return lst
else:
new_lst = lst[0:index]
new_lst.append(lst[index]*2)
new_lst = new_lst + lst[index+1:]
return new_lst

What does this lines does:
new_lst = new_lst + lst[index+1:]

Why it’s index+1 and not index+2\3\4 etc…why specifically 1?

Thanks

Welcome, @data1249767510,

Unfortunately that could not be the solution as the list should only have one value changed, and no new ones added.

Once we validate the index parameter, we need to access that element and multiply the value there by two, then reinsert it at that same index.

`````` lst[index] = lst[index] * 2
``````

That’s the extent of what needs to be done. Be sure to return `lst` and not `new_lst`.

Hi there,

I saw lots of people discussed this exercise, and when it comes to Error check then things is getting more and more complicated. Clearly the suggested solution from Codecademy is kindda simple and not enough.

We are discussing about the negative and positive index, but imagine what if we inputted a REAL number, instead of integer number?

Using try: and except: on IndexError will work, if we inputted an Integer, but if we input 1.2 instead of 1, 3, 4… something then come a Type Error. We also need to check if the lst is a realist.

At this point I think we should believe in and practice using all the material had been provided so far, but I am expecting more depth code will be provided in the next lesson.

Share with you guys my solution, surely not perfect and cannot predict all scenario of errors which could happen:

def double_index(lst, index):
try:
new_lst = lst[0:index]
new_lst.append(lst[index]*2)
new_lst = new_lst + lst[index+1:]
return new_lst
except IndexError:
return “Your index is invalid”
except TypeError:
return “Check type of your list or your index”

I came up with the code below. It has less steps to execute so in terms of run time, it would be more efficient. it passed the test. Let me know your thoughts.

``````>>> a = [3, 8, -1, 12]
>>> -1 in range(len(a))
False
>>> -1 in range(len(a)-1)
False
>>> 4 in range(len(a))
False
>>> 3 in range(len(a))
True
>>> 3 in range(len(a)-1)
False
>>>
``````

We can see from above that subtracting 1 from the range upper bound results in False when it should be True.

A lot of errant solutions slip under the radar of the SCT, but that does not mean they are correct.

We would never discourage anybody from posting, except when it comes to posting unexplained solutions, or errant ones. Neither helps anyone.