I’m not sure what I’m going wrong with my code for question four (Double Index). Seems to output the correct answer every time I’ve tested it. Why am I getting the " Make sure to define what should happen if index
is too big!"?
The question is as follows:
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.
Looking into this question I’ve found this one similar. Yet, pretty sure I’m following the question by creating a new list.
My code:
def double_index(lst, index):
#Saves the index integer to a variable to be doubled later
lst_index = lst[index]
#Doubles the lst_index while turning it back into a list so it can be concatinated.
double_index = [lst_index * 2]
#Gets the before and after parts of the origianl list
before_index = lst[:index]
after_index = lst[index + 1 :]
#Makes the new list
new_double_index_list = before_index + double_index + after_index
#The area I'm messing up in somehow. I've done greater than or equal to along with greater than which makes more sense to me. Neither work.
if index >= len(lst):
return lst
else:
return new_double_index_list
Edits:
#1 - Spelling
#2 - Added notes into code so it’s easier to follow.
#3 - Added link to the page