How to sort elements within a list of lists without altering the position of the elements in python?

Viewed 110

I have the list:

a = [[7, 3, 5], [9, 0, 3], [1, 2, 3]]

expected output:

b = [[7, 5, 3], [9, 3, 0], [3, 2, 1]]

Thank in advance!

4 Answers

You can use a list comprehension and use sorted(l, reverse=True) to sort each sublist in descending order

a = [[7, 3, 5], [9, 0, 3], [1, 2, 3]]
b = [sorted(l, reverse=True) for l in a]

You can loop over the list and call sort on each inner list.

a = [[7, 3, 5], [9, 0, 3], [1, 2, 3]]
for x in a:
    x.sort(reverse=True)
print(a)

I hope that this can help you

a = [[7, 3, 5], [9, 0, 3], [1, 2, 3]]
for idx, item in enumerate(a):
    item.sort(reverse=True)
    a[idx] = item

print(a)
Related