Hello All,

I'm trying to write a function that outputs the reverse of the input. I know that you can use the built-in list.reverse() or S[::-1] methods, but I want to make it using the 'for' loop. My code initially is:

def reverse(S)

    for x in S:
        print(x, end = " ")

the inputs would be

>>> reverse(['a','b','c']
['a','b','c']   #this is output on shell

Any ideas on how to reverse it and have the output be like below:

>>> reverse(['a','b','c']
['c','b','a'] 

Any help would be greatly appreciated. Thanks.

Edited 4 Years Ago by pyTony: Messed formatting fixed, use code blocks for code

I think that you probably have something like this in mind:

def print_reverse(s):
    for i in range(len(s)-1, -1, -1):
        print(s[i])

Edited 4 Years Ago by arkoenig: fixed typo

Sorry for the late feedback guys. Thanks for your inputs.

PyTonty, your code includes a built-in function, which I wanted to avoid, but thank you for showing me the reversed() function.

Arkoenig, your code is cool too. I did not know that was possible.

I finally figured out how to make a reversed list:

    def reverse_list(L):
        L2 = []
        for i in L:
            L2 = [i] + L2
        return L2

This way, we get a new list that is the exact revere of the original list.
Still, we have to create a new list. I guess there isn't any way to reverse the same list and return the same list backwards without using a built-in function.

Thanks!

This function is not printing like you said, here is one modifying the original by swapping:

def reverse_(L):
    half = len(L) // 2
    for offset in range(half):
        L[offset], L[-offset-1] = L[-offset-1], L[offset]

s = [1, 2, 3, 4, 5]
reverse_(s)
print(s)
This article has been dead for over six months. Start a new discussion instead.