How to sort by numbers a list that contains a mix of numbers as strings, numbers and strings in Python

1 Answer

0 votes
def to_number(x):
    try:
        return float(x)
    except ValueError:
        return float('inf')   # push non-numeric to the end

mixed_list = ["10", 16.8, "3.14", "abc", 5, "3", "xyz", 1, "44", 2]

sorted_mixed_list = sorted(mixed_list, key=to_number)
 
print(sorted_mixed_list)
 
 
   
'''
run:
   
[1, 2, '3', '3.14', 5, '10', 16.8, '44', 'abc', 'xyz']
   
'''

 



answered Jan 22 by avibootz
...