Home >Backend Development >Python Tutorial >How to Sort a List of String Numbers Numerically in Python?

How to Sort a List of String Numbers Numerically in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 17:57:12647browse

How to Sort a List of String Numbers Numerically in Python?

Sorting a List of String Numbers Numerically

Despite its simplicity, the Python sort() function can be misleading when dealing with strings representing numbers. As demonstrated in the code snippet below, attempting to convert these strings to integers and then sort them produces incorrect results:

list1 = ["1", "10", "3", "22", "23", "4", "2", "200"]
for item in list1:
    item = int(item)

list1.sort()
print(list1)

Output:

['1', '10', '2', '200', '22', '23', '3', '4']

To rectify this issue, you must actually convert your strings to integers. Here's the corrected code:

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

This outputs the correct numerical order:

['1', '2', '3', '4', '10', '22', '23', '200']

Alternatively, if you need to keep the elements as strings, you can use the key parameter in sort(). This parameter accepts a function that is called on each element before it is compared. The key function's return value is used for comparison instead of the element itself.

For instance:

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

or

list1 = sorted([int(x) for x in list1])

The above is the detailed content of How to Sort a List of String Numbers Numerically in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn