 # Advanced Python Code Challenges: Lists

Lists
I am struggling with this question. Can someone help me with the code:

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.
Q4

what code do you have so far? What are you struggling with?

You learn most if we guide you, but you have to solve the problem in the end I’m having the same difficulty with this question. I just cant think of a way to modify and index within a list and also check if the index is valid?
I’ve done it but I feel like the code is sketchy and not very robust.

``````#Write your function here
def double_index(lst,index):
if index <= len(lst)-1:
x = lst[index] * 2
lst2 = lst[index+1:]
return lst[:index] + [ x ] + lst2
else:
return "You're index is too big"

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

you can check if the index is valid first? If the index isn’t valid, you don’t need to modify the list.

why use list slicing? We can update an element in a list if we know the index in a much simpler way.

Hello @method2142069568!

Follow my code. I hope it can help.

``````def double_index(lst, index):
if index >= len(lst):
return lst
else:
lst[index]= 2*lst[index]
my_lst = lst[0:index] + lst[index: ]
return my_lst

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

why do this step:

``````my_lst = lst[0:index] + lst[index: ]
``````

you already doubled the index, the task is completed, why tear the list apart and put it back together?

Hello @stetim94

The exercise asks to double the index and print the list contending it. Because of that, the following step after doubling the index, it is complete the list with :

``````my_lst = lst [0:index] + lst [index:]
``````

Regards!

That is not my point. That specific line of code is totally redundant. That is my point Hi @cristss,

The second paragraph begins as follows:

The function should return a new list …

So, yes, this is the line in which you create a new list:

``````    my_lst = lst[0:index] + lst[index: ]
``````

However, as @stetim94 points out, your `double_index` function does the unnecessary work of creating the new list from separate parts of the original list.

Note that you have also modified the original list in the previous line of code. It would be best to leave the original list in its original condition. You could simply copy the original list, then modify and return the copy.

Got it. Thanks! 1 Like

Thanks @appylpye ! 1 Like