Advanced Python Code Challenges: Lists, #4: Double Index


Could someone explain what I am doing wrong here? I thought it out logically and am stumped at my errors. Thank you!


Create a function named double_index that has two parameters: a list named lst and a single number named index .

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

If index is not a valid index, the function should return the original list.


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

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

"TypeError: List object is not callable


if lst[index] > len(lst):

you still try to access the list by index (lst[index]), so if the index is out of range/bound, you will get an error.

Not sure what you do here:

    replace = (lst[index] * 2)
    new = lst[:lst[index]] + lst(replace) + lst[lst[index] + 1:]

looks really complex, if we know the index, we can simply update the element at that index, why would we need list slicing?


Yes is there a way to do this without slicing? Just to keep the list intact and only impact the index? seems like there should be.

Hello @vszybala, welcome to the forums! Yes, there is, and it involves the fact that lists are mutable, meaning you can change things within them:

some_list = [1, 2, 3, 4]
some_list[2] = 2
>>[1, 2, 2, 4]
1 Like

Although @codeneutrino is right, given you already know what you are after, you can simple google something like: python update element in list

1 Like