Index replacement isn't accepted?

possible spoiler to the problem follows

Okay, I think I need some guidance.

The following code returns the correct answer and, I think, deals with the valid index problem. But the page won’t confirm that, and returns: "Double the value at position index in lst"

The code does so, and prints the right answer, but the page doesn’t agree and won’t accept it.

Here’s the code:

> def double_index(lst, index):
>   lst[2] = lst[2] * 2
>   return lst
>   if index >= len(lst):
>     return lst
> 
> print(double_index([3, 8, -10, 12], 2))

Any help appreciated. Thx

Our function won’t know that 2 is the intended index, hence the parameter, index.

if index < len(lst):
    lst[index] *= 2
return lst
1 Like

That was really helpful, thank you.

1 Like

Also, that’s the most elegant version of the code I’ve seen.

We can make it handle all valid indices, bottom to top,

n = len(lst)
if -n <= index < n:

As solutions go, the most elegant one still has to pass muster. What edge cases can it endure? This may not be an example of said interrogation of the matter, but that is the form of scrutiny we must apply to all our code models.

When, and only when one’s code passes all scrutiny should refactoring come into play. We must understand the base form before adopting its analogs.


Simplest example…

a = 1
a = a + 1
a += 1
print (a)
# 3

Thank you so much. I could, and still can’t, understand the solution given. This makes perfect sense.

1 Like