Python Code Challenges (Optional) Advance Lists, Challenge 4. Double Index

Hi there,

I’m going through the Computer Science career path and I’ve reahed the optional Python challenges. This one in particular requires to double a value at a given position provided 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 it should return the original list.

I did come up with this code:

#Write your function here def double_index(my_list, index): #Checks if index is too big if index - 1 > len(my_list): return my_list else: #Creates new list with data up to and after the index new_list = my_list[:index] + my_list[index+1:] #Inserts the ouble of the index in the original index place new_list.insert(index, my_list[index]*2) return new_list #Uncomment the line below when your function is done print(double_index([3, 8, -10, 12], 2))

However on testing it comes up with the message: Make sure to define what should happen if index is too big! But I have done that… It’s the first part of my if :confused:

The suggested solution is as follows:

def double_index(my_list, index): # Checks to see if index is too big if index >= len(my_list): return my_list else: # Gets the original list up to index my_new_list = my_list[0:index] # Adds double the value at index to the new list my_new_list.append(my_list[index]*2) # Adds the rest of the original list my_new_list = my_new_list + my_list[index+1:] return my_new_list

Now, index >= len(my_list) it’s virtually the same than index - 1 > len(my_list) so I really don’t understand why it’s coming up with an error. Any ideas?

Check the indentation of your code. It is not correct, so your code is returning nothing.

Check your math. You may need a plus instead of a minus.

What happens for double_index([3, 8, -10, 12], 4) ?

I think you’re right… I was doing the maths the other way :woman_facepalming: :sweat_smile:

Thanks very much!

What about your indentation? Maybe that is the issue. I have otherwise run your code on my sandbox and it works just fine :confused:

promise = “I will work hard”
for _ in range(5):
TAB print(promise)