0

Can somebody help me understand why I'm getting this result?

I'm trying to reverse this list using indexing.

def reverse_list(nums):
    for i in range(len(nums)):
        nums[i] = nums[-i-1]  # I think the problem is here in the assigning part

numbers = [1, 2, 3, 4]
reverse_list(numbers)

Output:

[4, 3, 3, 4]

Desired output:

[4, 3, 2, 1]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    Welcome to Stack Overflow! Check out the [tour] and [ask] for tips like how to write a good title. You might want to learn [How to step through Python code to help debug issues](/q/4929251/4518341) (I recommend Python Tutor for beginners) and [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) in general. – wjandrea May 04 '23 at 23:35
  • You might also want to read [How to ask and answer homework questions](https://meta.stackoverflow.com/q/334822/4518341). I assume this is homework because otherwise you'd just use `numbers.reverse()`. – wjandrea May 04 '23 at 23:46

1 Answers1

3

After you do nums[i] = nums[-i-1] you no longer have the original value of nums[i] in the list. So you won't be able to assign that to the corresponding element at the other end.

You need to swap the elements, not just assign one. And you should only iterate halfway through the list, otherwise you'll just end up swapping them back when you get to the second half.

def reverse_list(nums):
    for i in range(len(nums) // 2):
        nums[i], nums[-i-1] = nums[-i-1], nums[i]
Barmar
  • 741,623
  • 53
  • 500
  • 612