0

I have this list like this:

list1 = [["A",5,2,8,3],["B",9,5,1,5]]

And I'm trying to sort it by the second column. I would expect list1 to then be

[["B",9,5,1,5],["A",5,2,8,3]]

Because 9 is greater than 5 right? I'm using

sorted(lis1, key=lambda a : a[1])

however it doesn't sort it; it just remains as it was before. Why isn't this working?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Alster
  • 21
  • 2
  • It sorts in ascending order by default. Add the argument `reverse=True` to your `sorted` function to generate the desired output – gtlambert Feb 29 '16 at 21:13

3 Answers3

2

sorted:

Return a new sorted list from the items in iterable

It does not sort in place.

1

You just need to reverse it:

list1 = [["A",5,2,8,3],["B",9,5,1,5]]
list1 = sorted(list1, key=lambda a : a[1], reverse=True)
print(list1)
# outputs [["B",9,5,1,5],["A",5,2,8,3]]

9>5, so it comes afterwards, unless you reverse.

rofls
  • 4,993
  • 3
  • 27
  • 37
0

using operator.itemgetter() function:

from operator import itemgetter

list1 = [["A",5,2,8,3],["B",9,5,1,5],["C",1,2,8,3]]

print(sorted(list1, key=itemgetter(1)))
print(sorted(list1, key=itemgetter(1), reverse=True))

Output:

[['C', 1, 2, 8, 3], ['A', 5, 2, 8, 3], ['B', 9, 5, 1, 5]]
[['B', 9, 5, 1, 5], ['A', 5, 2, 8, 3], ['C', 1, 2, 8, 3]]
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419