Can someon check my answer vs the solution and give me feedback on my answer?

Hello, this is for question #5 in https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-lists/articles/advanced-python-code-challenges-lists

#Write your function here

def double_index(lst, index):
  if index > len(lst):
    return "Index is out of range" 
  else:
    new_index_number = lst[index] * 2
    lst[index] = new_index_number
    return lst

#Output gives me the correct answer, doubling the value in index of two. [3, 8, -20, 12]

#Uncomment the line below when your function is done

print(double_index([3, 8, -10, 12], 2))


///////////////////////



But here is the solution provided:

#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))

Why is it better than mine? Or is it?

Welcome back to the forums!

The instructions state that you should return a new list, rather than modify the old one. Your code is currently modifying the original list, while the solution provided creates and returns a new one. Try tackling this exercise again!

1 Like

My way is cooler! :slight_smile: thanks for your response

It doesn’t follow the instructions. Therefore you didn’t really solve the exercise.

As @h1lo said, you’re not accomplishing what the exercise asks you to do. What if you needed to access the original list afterwards? You can’t, because you’ve changed it. Fix this before moving on.

2 Likes