Can someone explain to me why this sort is going all wonky on me? And a how to fix would be cool too. Thanks

``````>>> a = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
>>> a
['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
>>> a.sort()
>>> a
['10', '10', '11', '11', '12', '12', '13', '13', '14', '14', '15', '15', '16', '16', '2', '2', '3', '3', '4', '4', '5', '5', '6', '6', '7', '7', '8', '8', '9', '9']``````

Strings are sorted first by their first letter so 'ab' < 'c' or '10'<'3'

## All 4 Replies

Strings are sorted first by their first letter so 'ab' < 'c' or '10'<'3'

Oh. Right. Thanks. Makes sense now.

A couple of way to make it a list of integer and sort.
First one use list comprehension.
Second one use a function programming style with map().

``````>>> print sorted([int(i) for i in a])
[2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16]

>>> print sorted(map(int, a))
[2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16]``````

Yeah, I solved it with a comprehension

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.