Categories
Python Answers

How to sort a list of strings numerically with Python?

Spread the love

Sometimes, we want to sort a list of strings numerically with Python.

In this article, we’ll look at how to sort a list of strings numerically with Python.

How to sort a list of strings numerically with Python?

To sort a list of strings numerically with Python, we convert the strings in the list to numbers before we sort them.

For instance, we write

list1 = ["1", "10", "3", "22", "23", "4", "2", "200"]
list1 = [int(x) for x in list1]
list1.sort()

to convert all items in list1 to ints with

[int(x) for x in list1]

and assign the returned result back to list1.

Then we call sort to sort the items in place.

Conclusion

To sort a list of strings numerically with Python, we convert the strings in the list to numbers before we sort them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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