-1

When I try to sort a list of strings of numbers with the following code it gives me a wrong result.

n = list(input().split())

n.sort()

print(n)

for input = 10 11 100 200 300 34 , after sorting it gives ['10', '100', '11', '200', '300', '34'] where output should be '10', '11', '34', '100', '200', '300']

Sourabh
  • 8,243
  • 10
  • 52
  • 98
S sharma
  • 11
  • 6
  • 4
    Possible duplicate of [How to sort python list of strings of numbers](https://stackoverflow.com/questions/17474211/how-to-sort-python-list-of-strings-of-numbers) – Cuppyzh Aug 22 '19 at 14:24
  • hi @yatu i tried but it shows vote casted by less than 15 reputation are not counted. BTW thanx – S sharma Aug 25 '19 at 11:50

2 Answers2

2

The problem is that the list contains strings, and strings are sorted lexicographically. You need to cast the list items to int, then sort:

n = list(map(int, input().split()))
n.sort()
print(n)
# [10, 11, 34, 100, 200, 300]

Or if you want the resulting list to contain strings:

print(list(map(str, n)))
yatu
  • 86,083
  • 12
  • 84
  • 139
0

The wrong output you are receiving is due to lexical sorting instead of numerical sorting being applied, because you are operating on string.

What you want is:

n = [int(i) for i in input().split()]

n.sort()

print(n)
Greg
  • 43
  • 6