goku
goku

Reputation: 327

how to reverse the order of the output

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

Upvotes: 2

Views: 1573

Answers (2)

Sharim09
Sharim09

Reputation: 6224

for i in range(10)[::-1]:
    print(i)

OUTPUT

9
8
7
6
5
4
3
2
1
0

Upvotes: 1

mozway
mozway

Reputation: 261860

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

Upvotes: 4

Related Questions