Python sort list of strings with numbers | Example code

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

list.sort(key=int)

or with float

sort(key=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)

Output:

Python sort list of strings with numbers

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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.