Double_index

Is my answer to this exercise not as robust as Codecademy’s?

I’ve pasted the link to the exercise, my code below the link, and finally, Codecademy’s solution.

https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-lists-cc/exercises/double-index?action=resume_content_item

my code:

#Write your function here
def double_index(lst, index):
if index >= len(lst):
return lst
else:
lst[index] = lst[index] * 2
return lst

#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 3))

The 'solution:

#Write your function here
def double_index(lst, index):
if index >= len(lst):
return lst
else:
new_lst = lst[0:index]
new_lst.append(lst[index]*2)
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))

Hello, @overcantor.

The instructions ask us to return a new list leaving the original intact. Your code mutates the original list.

You could still use the same logic. Just perform the action on a copy of the original list.

1 Like

Thank you for your help!

2 Likes