Ok, so, I’m utterly confused by question 4 of the python lists challenges here: Python Lists | Codecademy
So this is the challenge here and honestly I’ve read it over 6 or 7 times, even looked over the answer a number of times but I’m so lost. I’m starting to think its just written badly but if somebody could clear this up for me that would be amazing. I think I’m struggling with the difference between Value and Element in particular.
- Double Index
Our next function will double a value at a given position. We will provide a list and an index to double. This will create a new list by replacing the value at the index provided with double the original value. If the index is invalid then we should return the original list. Here is what we need to do:
Define the function to accept two parameters, one for the list and another for the index of the value we are going to double
Test if the index is invalid. If its invalid then return the original list
If the list is valid then get all values up to the index and store it as a new list
Append the value at the index times 2 to the new list
Add the rest of the list from the index onto the new list
Return the new list
Create a function named double_index that has two parameters: a list named lst and a single number named index.
The function should return a new list where all elements are the same as in lst except for the element at index. The element at index should be double the value of the element at index of the original lst.
If index is not a valid index, the function should return the original list.
For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled:
double_index([1, 2, 3, 4], 2)
After writing your function, un-comment the call to the function that we’ve provided for you to test your results.
We can use slicing to get the values up to an index lst[0:index] and from an index to the end lst[index+1:]. Also, to append to the end of a list we can use the append() function.
#Write your function here def double_index(lst, index): # Checks to see if index is too big if index >= len(lst): return lst else: # Gets the original list up to index new_lst = lst[0:index] # Adds double the value at index to the new list new_lst.append(lst[index]*2) # Adds the rest of the original list new_lst = new_lst + lst[index+1:] return new_lst #Uncomment the line below when your function is done print(double_index([3, 8, -10, 12], 2))
The code makes sense to me but the instructions are really confusing, is that just me? Are there basic concepts that I’m lacking understanding in?