Skip to content

Python sort list of strings with numbers | Example code

  • by

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']




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

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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