0

Could someone explain to me how this python loop outputs the reverse order of elements in a list? This was part of a school assignment and I can't quite comprehend how this works.

I know this is a more difficult way of obtaining the reverse order of a list, but we were not allowed to use the reverse function and I could not seem to get list splicing to pass the autograder.

def reverse_list(stuff):
    '''Function that reverses the order of elements in a list'''
    i = 0
    n = len(stuff)-1
    while i<n:
        temp = stuff[i]
        stuff[i] = stuff[n]
        stuff[n] = temp
        i+=1
        n-=1
#test
stuff = [1,2,3,4]
reverse_list(stuff)
print(list) #Output [4,3,2,1]
1
  • temp isn't necessary; stuff[i], stuff[n] = stuff[n], stuff[i]. Commented Nov 9, 2019 at 18:15

1 Answer 1

1

Using better names, and a print you may better understand

def reverse_list(stuff):
    begin = 0
    end = len(stuff) - 1
    while begin < end:
        temp = stuff[begin]
        stuff[begin] = stuff[end]
        stuff[end] = temp
        begin += 1
        end -= 1
        print(stuff)

For input [1, 2, 3, 4, 5, 6, 7, 8, 9] you'll see

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 2, 3, 4, 5, 6, 7, 8, 1] # swap 1 and 9
[9, 8, 3, 4, 5, 6, 7, 2, 1] # swap 2 and 8
[9, 8, 7, 4, 5, 6, 3, 2, 1] # swap 3 and 7
[9, 8, 7, 6, 5, 4, 3, 2, 1] # swap 4 and 6

The way is, getting two indexes

  • one starting at the beginning and incrementing : begin
  • one startting at the end and decrementing : end

And each time on swap then using a third variable temp, and 2 by 2 you're going to swap all, until you reach the middle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.