AmericanMade AmericanMade - 5 months ago 13x
Python Question

Sort list of ints by the first digit of each int Python

I'm trying to figure out how to sort a list of integers by the first digit in each int, (and if the same, move to the next digit, etc.)

I'm sure I can just loop through, (although I've been having issues because it seems like I need to make my list a list of strings in order to grab the first digit and this just hasn't been working out for me), but I'd like to know if there is a way to do this easily with the sorted() method.


myList = [34254, 2343, 49, 595, 323]

My desired result:

sortedList = [2343, 323, 34254, 49, 595]

Thanks for any help! I've been looking all over, but I just get answers about doing it in Excel.


Sort with a key of strings and you'll get ASCIIbetical sorting.

>>> myList = [34254, 2343, 49, 595, 323]
>>> sorted(myList, key=str)
[2343, 323, 34254, 49, 595]