Help with Double Index activity


#1

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

I don’t understand what the directions are asking me to do. I don’t understand why I have to understand the length of 1st. It is also throwing me off that I can’t see the values of 1st and index. I don’t understand what it means by a “valid index”. Can someone help me to decipher this lesson?

Below is the correct code to the lesson in which I don’t understand.

I will also include the instructions:
Create a function named double_index that has two parameters named lst and index .

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.

After writing your function, un-comment the call to the function that we’ve provided for you to test your results.


#2

Have you been reading and re-reading the lesson text leading up to this exercise. It’s all pretty well explained.

a_list = [3, 8, -10, 12]

The indexes of this list are 0, 1, 2, 3, and the length is 4. Notice that the index of the last element is 1 less than the length? That means a valid index cannot equal the length. We are given a list and an index. Our function should validate the index (make sure it is in range) and if valid, double the element value at that index in the list.

We can see the values of lst and index in the function call.

double_index([3, 8, -10, 12], 2)
             [---- lst ----]  ^
                            index

#3

Thank you so much! I appreciate it. I am currently redoing all of the lessons before. I do understand it better now.


#4

Since we want our index to be in range it makes perfect sense to use Python to help validate it…

if index in range(len(lst)):

Now we know it is in range since it is in the range we need it to be in. Recall that index might be negative. That would be less than the length, but also out of range, especially if it is less than negative length. (those greater or equal would be indexed from the right).

lst[-1] .. lst[-len(lst)]

are in range, just in reverse.