Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort integer list in python descending order

Tags:

python

list

I have tried to figure this out in different ways, to no success. I keep getting ascending order sort, rather than descending order when I print.

ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
sorted(ListB, key=int, reverse=True)
print sorted(ListB)
like image 969
Math4CT Avatar asked Aug 19 '14 00:08

Math4CT


2 Answers

You are printing the list sorted ascending:

print sorted(ListB)

If you want it descending, put your print statement on the previous line (where you reverse it)

print sorted(ListB, key=int, reverse=True)

Then remove your final print statement.

Example:

>>> ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
>>> print sorted(ListB, key=int, reverse=True)
[48, 46, 25, 24, 22, 13, 8, -9, -15, -36]
like image 72
Andy Avatar answered Sep 30 '22 05:09

Andy


Try this, it'll sort the list in-place in descending order (there's no need to specify a key in this case):

listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
listB.sort(reverse=True) # listB gets modified

print listB
=> [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]

Alternatively, you can create a new sorted list:

listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
listC = sorted(listB, reverse=True) # listB remains untouched

print listC
=> [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]
like image 31
Óscar López Avatar answered Sep 30 '22 06:09

Óscar López