What are the possible ways of reversing order of any output?
For example, if I have a code like this:
for i in range(10):
print(i)
This is fairly a simple example of course. I can just say
for i in range(9, -1, -1):
print(i)
But what happens when you have very complicated functions, lists, maps, arrays, etc. So my question is: Is there a generic way (or ways) to reverse the order of any output?
I've been thinking about pushing every element (element can be anything) onto a stack, then pop() elements and printing the popped element. But maybe there are better solutions
CodePudding user response:
You can use the reversed
builtin:
for i in reversed(range(10)):
print(i)
output:
9
8
7
6
5
4
3
2
1
0
CodePudding user response:
for i in range(10)[::-1]:
print(i)
OUTPUT
9
8
7
6
5
4
3
2
1
0