Need help with List code

Hi I am new to python and doing some online practice exercises on different websites.
I came across this code with multiple choice questions.
Now the following is a list with 4 numbers .This is the question.

numbers = [2,3,5,8]

now the user/student has to select two options that will not raise exceptions.

The first answer is :
numbers[numbers[1]

Explanation given on the website is as follows:

is actually numbers[3] which evaluates to 8 and no exception is raised.
Now I don’t understand how it evaluates to 8 .I thought the answer would be 3 as index[1] has number 3.Can someone please explain ?

Also I want to know why this option will raise exception
numbers[numbers[3]]

Explanation on the website is as follows:

is actually numbers[8] which will raise exception.Why?

Please help me its very annoying I can’t move before I understand this code. :slight_smile:

For starters we need to understand what the code fundamentally does. For any numbers[numbers[x]] we are getting the value at one index (x) and then using that value to get the value at another index. If we broke it up into two lines (and added some variable names) it would look like this:

y = numbers[x]
result = numbers[y]

So y is the value stored at the original index (x) and that number is used as a new index in the same list to get our result.

Now applying the original numbers[numbers[1]]:

y = numbers[1]  # y = 3
result = numbers[y]  # result = numbers[3] = 8

This works because the value at numbers[1] happens to be a valid index in the numbers list. But look what happens with numbers[numbers[3]]:

y = numbers[3]  # y = 8
result = numbers[y]  # result = numbers[8] = uh oh

In that case the value at numbers[3] was 8 which is not a valid index in the numbers list so we get an exception.

3 Likes

Thank you so much.You explained it so well.Thanks a lot :slight_smile: