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.

## All 4 Replies

def print_reverse(s)
for x in reversed(s):
print(x, end = " ")

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])

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.