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 can use the int function to convert the number strings into integers.

Then we call sort on the integer array to sort the integers.

For instance, we write:

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

We convert each string to integers with [int(x) for x in list1], return that in an array, and assign it to list1.

Then we call list1.sort to sort the integer array in place.

Therefore, list1, is [1, 2, 3, 4, 10, 22, 23, 200].

Conclusion

To sort a list of strings numerically with Python, we can use the int function to convert the number strings into integers.

Then we call sort on the integer array to sort the integers.

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 *