Python: sorting string numbers not lexicographically

You can use the built-in sorted() function with a key int to map each item in your list to an integer prior to comparison:

numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

Output

['8', '10', '918', '101010']

Using this method will output a list of strings as desired.

Leave a Comment