1

I have a list of tuples sorted by the second element like so:

[('7', 10), ('2', 9), ('8', 9)]

I would like to sort them by their first element like so:

[('2',9),('7', 10),('8', 9)]

I have tried:

test_val = [('7', 10), ('2', 9), ('8', 9)]
test_val.sort(key=lambda x: x[0])

which I found from here

However, the list is not sorted.

Real data example:

Before Attempt:

[('7', 10), ('2', 9), ('8', 9), ('6', 8), ('24', 8), ('3', 7), ('5', 7), ('9', 6), ('35', 6), ('15', 5), ('16', 5), ('1', 4), ('14', 4), ('17', 3), ('19', 3), ('12', 2), ('39', 2), ('26', 1), ('25', 1), ('22', 0)]

After Attempt:

[('1', 4), ('12', 2), ('14', 4), ('15', 5), ('16', 5), ('17', 3), ('19', 3), ('2', 9), ('22', 0), ('24', 8), ('25', 1), ('26', 1), ('3', 7), ('35', 6), ('39', 2), ('5', 7), ('6', 8), ('7', 10), ('8', 9), ('9', 6)]
Community
  • 1
  • 1
Turtle
  • 1,369
  • 1
  • 17
  • 32

1 Answers1

5

The list is, too sorted. Note that your sort key is a string, not an integer. Perhaps what you want is

test_val.sort(key=lambda x: int(x[0]))
Prune
  • 76,765
  • 14
  • 60
  • 81