Python 3 - double index exercise

Hello. I don’t understand a part of the solution of the double index exercise https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-lists

The full answer to this exercise is:
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
print(double_index([3, 8, -10, 12], 2))

Could you please explain the below part?
new_lst.append(lst[index]*2)
is the append function not adding an element at the end of a list?

Also, I am not sure why we put +1:
new_lst = new_lst + lst[index+1:]

Thank you in advance for your help.

Hello @joannastroz270069404, welcome to the forums!
This code here:

Sets a new list equal to the contents of the old list up to the index provided:

[1, 2, 3, 4, 5, 6] , 2 #list and index  
#This code appends 1, 2 to the new list, as they come before the index 2.

The code here:

Then appends the item of the original list at the position index, doubled. Take the same data as above:

original_list:[1, 2, 3, 4, 5, 6]
new_list:[1, 2](Remember we appended these two values with the above code?
new_list.append(3 * 2) The item at index 2 in the original list is three
new_list = [1, 2, 6](the doubled item is now at the end of the list

This code:

Now appends the rest of the original list to the new list. The reason it is index+1 is because the starting value is inclusive, which means if you just had index, the first number added would be the number you doubled:

[1, 2, 3, 4, 5, 6]-list
0, 1, 2, 3, 4, 5-index
#If there was no +1 then we would get this (remember the example above) same data:
new_list = [1, 2, 6, 3, 4, 5, 6]
#This is because we double the item at index, and then add the item at index
#to the new list.

The plus one sign stop us doing that:

[1, 2, 3, 4, 5, 6]-list
 0, 1, 2, 3, 4, 5-index
new_list = [1, 2, 6]
new_list + newlist[index + 1:]
new_list = [1, 2, 6, 4, 5, 6]
#Here we appended the item at index doubled (3 *2=6), to the new list
#then we appended the rest of the original list, excluding the item we doubled

The : sign in the code:

Just means “from this position to the end of the list”.
I hope this helps!

1 Like

Hello @codeneutrino, thank you so much for such a quick reply.

Your explanation is extremely clear! Now I understand each step.

Thank you very much for explaining it in details.

Take care!

2 Likes

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

Good job, I’m glad you got it to work! Was there a specific question/statement you wanted to say?
Happy coding!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.