If you have a list of strings but contain the number and want to sort it then use the sort method with key=float to sort the list.
Sort list of strings with numbers
or with float
Example Sort numeric strings in a list in Python
Simple python example code.
Using sort() + key
You could pass a function to the key parameter to the .sort method. With this, the system will sort by key(x) instead of x.
list1 = ['4', '6', '7', '2', '1'] list1.sort(key=int) print(list1)
sorted() function + key
In case you want to use
sorted() the function:
sorted(list1, key=int). It returns a new sorted list.
This function offers than the above function is that it doesn’t change the order of the original list.
list1 = ['4', '6', '7', '2', '1'] print(sorted(list1, key=int))
Do comment if you have any doubts and suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.