How should I write the code with the following problem?
Implement the function reverse_print(lst) that prints out the contents of the given list ‘lst’ in reverse order. For example, given a list [3, 6, 2, 1], the output should be 1, 2, 6, 3 (vertical printout allowed). For this code, you are only allowed to use a single for-loop. Without String Method
Also Not using Print[::-1]
CodePudding user response:
Assuming you are not allowed to just call list.reverse()
you can use range
with a negative step to iterate the list in reverse order:
def reverse_print(lst):
out = []
for i in range(len(lst) - 1, -1, -1):
out.append(lst[i])
print(*out, sep=", ")
inp = [1, 2, 3, 4]
reverse_print(inp)
Output: 4, 3, 2, 1
CodePudding user response:
You may try something like this
def reverse_print(lst):
rev = [lst[abs(i-l)-1] for i in range(l)]
return rev
lst = [3,6,2,1]
l = len(lst)
print(reverse_print(lst))