Code challenge: Lists - Double Index, index error

Hi, I need help in identifying error in the code below.

#The function should return a new list where all elements are the same as in 'lst' except for the element at 'index', which should be double the value of the element at index of lst.

def double_index(lst, index):
  temp_lst = []
  for i in range(len(lst)):
    if i != index:
      temp_lst[i] = lst[i]
      temp_lst[i] = 2 * lst[i]
  return temp_lst

print(double_index([2, 3, 8, 9, 10, 1], 3))

Why would you use a loop? You only need to update a single element

as for the actual error (just for learning sake), its here:

temp_lst[i] = lst[i]

temp_list is empty, so even for i=0, this will give an index error. You could solve this by using .append() or by making temp_lst a copy of lst

but i would recommend rethinking your approach. You don’t need a loop, you only need to update a single element (of which the index has already been given)

1 Like