'How to sort integer list in python descending order

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)


Solution 1:[1]

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]

Solution 2:[2]

ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]

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

print ListB

Sorted does not change the variable passed to it. So if you want to do anything with them you have to store sorted output into a variable.

Solution 3:[3]

reversed(sorted(listb))

This creates an iterable going from 48 -> -36

Solution 4:[4]

u should have combined these two lines of code together, using this instead.

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

result:

[48, 46, 25, 24, 22, 13, 8, -9, -15, -36]

Solution 5:[5]

In Python you can sort as follows:

listA = [150, 120, 100, 165, 190, 145, 182, 175, 17]
print(sorted(listA))
print(sorted(listA, reverse=True))

This would be the actual implementation using selection sort:

# Traverse through all array elements
for i in range(len(listA)):

    # Find the minimum element in remaining
    # unsorted array
    min_idx = i
    for j in range(i + 1, len(listA)):
        if listA[min_idx] > listA[j]:
            min_idx = j

    # Swap the found minimum element with
    # the first element
    listA[i], listA[min_idx] = listA[min_idx], listA[i]

print(listA)

# Traverse through all array elements
for i in range(len(listA)):

    # Find the minimum element in remaining
    # unsorted array
    min_idx = i
    for j in range(i + 1, len(listA)):
        if listA[min_idx] < listA[j]:
            min_idx = j

    # Swap the found minimum element with
    # the first element
    listA[i], listA[min_idx] = listA[min_idx], listA[i]

print(listA)

Solution 6:[6]

ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
ListB.sort()
print(ListB[::-1])

This should work

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Jakob Bowyer
Solution 4
Solution 5 miquelvir
Solution 6 LIVI_py