-1

I want to sort a list containing integers as chars. e.g:

l = ['1', '10', '11', '12', '16', '17', '2', '24', '26', '27', '28', '30', '32', '34', '35', '36', '43', '45', '47', '49', '50', '6', '9']
print(sorted(l))

is returning:

['1', '10', '11', '12', '16', '17', '2', '24', '26', '27', '28', '30', '32', '34', '35', '36', '43', '45', '47', '49', '50', '6', '9']

why sorted() is acting unusually?

kestrel
  • 126
  • 1
  • 16

1 Answers1

2

Sorted is acting exactly as it should.

These are strings, not integers, so sorted sorts first by the first character, then by the second character.

If we want to sort ['1', '2', '12'], we get ['1', '12', '2']:

1
12
2

sorted first sorts by the first column, then by the second column.

Daniel
  • 3,188
  • 14
  • 34