I'm returning the doubled value, why isn't it working?

Can anyone shed some light on why it is not accepting my code? When I run the function I get the right answer, which is -20.

def double_index(lst, index):
if index < len(lst):
return lst[index] * 2
return lst

The solution insists on re-defining list[index] as the formula like so:

lst[index] = lst[index] * 2

but I don’t understand why this is necessary. Why can’t I just return the formula? The answer is the same.

That line is only returning a value, not the complete, amended list.

Formulae are for science and maths, in programming it is called a statement. The object on the left is being assigned the expression on the right of the assignment operator.

In maths there is no such thing as,

a = a * 2

since it clearly would not make any sense. But if we consider that a is just a name that identifies a value in memory, we can update the value it identifies. We take its current value, apply the arithmetic to that value, then assign the outcome back to that name.

What we’re actually doing in Python, if we treat a as a tag and the value as a hook, is to move the tag to a new hook.

1 Like