There are two problems. Let's take a look.
Problem 1: You don't just want to copy the items at the end to the beginning because that overwrites the ones at the front. You're getting [9, 12, 12, 9]
because the items at the front are being overwritten by the ones at the back.
Solution 1: Swap the elements. Python allows for a clever way of swapping two values without requiring a temporary variable:
for index in range(len(vals)):
n -= 1
vals[index], vals[n] = vals[n], vals[index]
Problem 2: If you run this you might be confused because vals
is unchanged:
[7, -3, 12, 9]
It looks like swapping didn't fix it. But that's because you have two problems. Swapping is correct, but it's not enough.
Before we jump to the solution, let's talk about how to diagnose the cause. A bread and butter debugging technique is inserting printouts to check intermediate results. Add a printout, make a mental prediction of what the result will be, and then run the program and see if you were right.
I might add a printout like this:
for index in range(len(vals)):
n -= 1
print("Swapping vals[{}]={} with vals[{}]={}.".format(index, vals[index], n, vals[n]))
vals[index], vals[n] = vals[n], vals[index]
I'd expect items 0 and 3 to be swapped and items 1 and 2 to be swapped. Is that what happens?
Swapping vals[0]=7 with vals[3]=9.
Swapping vals[1]=-3 with vals[2]=12.
Swapping vals[2]=-3 with vals[1]=12.
Swapping vals[3]=7 with vals[0]=9.
[7, -3, 12, 9]
Hm, that doesn't seem right. There are four swaps, not two. We swapped vals[1]
with vals[2]
, and then vals[2]
with vals[1]
. Whoops!
Solution 2: You need to stop half way through the list so that you don't swap all the items twice. If you swap positions 1 and 5, say, you don't want to also swap positions 5 and 1. Loop over half of the indices and then stop.
for index in range(len(vals) // 2):
n -= 1
vals[index], vals[n] = vals[n], vals[index]