Code Challenges_Advanced Lists_ Exercise4_DoubleIndex Alternative Solution?

https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-lists

Hello Community,
In exercise 4 in the advance code challenges for Lists under the Python 3 Pro course, one is asked to create a function that doubles the value of an element in a list when given its index. The function will then return a list with the updated value. In the case the provided parameter for the index is not valid, the function shall return the original input list without any changes.

I provided the following code to the Code Academy editor:

def double_index(lst, index): 
  if len(lst) < abs(index): 
    return lst 
  new_lst = lst 
  new_lst[index] = 2 * lst[index] 
  return new_lst

I believe my code satisfactorily passes the relevant tests for this exercise (What to do when an index is not valid, it also allows to input a negative index. However, the code editor did not accept this solution.

The answer provided by Codecademy is the following:

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

Is there a problem with my code? Why is not being accepted as an answer? I understand Codecademy algo. can not foresee every possible answer, but I believe my solution is very predictable.

I am happy to accept any feedback about my solution
Thanks in advance for answering my question!

Sorry, if I did not follow any guidelines for asking questions, this is my first post.

What happens when the index is equal to the length of the list?

lst = [1,2,3]
len(lst)
>>3
lst[3]
>>throws an error
2 Likes

Thank you for the idea codeneutrino!

I edited my code to:

def double_index(lst, index): 
  if len(lst) < abs(index) or len(lst) == index : 
    return lst 
  new_lst = lst 
  new_lst[index] = 2 * lst[index] 
  return new_lst

The editor accepted my answer. Thank you for providing the solution to my problem.

2 Likes