Fishhy
Fishhy

Reputation: 35

How can i print in descending order?

Below is my code I have printing this in ascending order I now need to print it in descending order but don't know how?

list = [37,-59,4,0,15,-12,9,0]

Upvotes: 2

Views: 4756

Answers (3)

StephenTG
StephenTG

Reputation: 2647

If you need the list both in ascending and descending order, you can get your list in reverse like so:

sorted_list_oldskool[::-1]

If you only need it in descending order, AMACB's answer is probably the most efficient.

If, for whatever reason you want to take your existing sorting logic and have it produce a list in descending order, you should change

if unsorted_list[i] <= sorted_list_oldskool[j]:

to

if unsorted_list[i] >= sorted_list_oldskool[j]:

Upvotes: 0

goto112
goto112

Reputation: 5

If I understood you correctly

print("Old way : ",sorted(sorted_list_oldskool, reverse=True))

Upvotes: 0

AMACB
AMACB

Reputation: 1298

Why don't you use the built-in sorted function?

>>> unsorted_list = [37,-59,4,0,15,-12,9,0]
>>> sorted(unsorted_list)
[-59, -12, 0, 0, 4, 9, 15, 37]
>>> sorted(unsorted_list,reverse=True)
[37, 15, 9, 4, 0, 0, -12, -59]

Upvotes: 1

Related Questions