-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
  • 7,921
  • 9
  • 48
  • 91
S sharma
  • 11
  • 5
  • 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 @henry don' forget you can upvote and accept answers, see [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers), thanks – yatu Aug 23 '19 at 15:31
  • 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
  • Yess but you can accept answers @henryallen, see the link [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – yatu Aug 25 '19 at 16:14

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
  • 80,714
  • 11
  • 64
  • 111
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
  • 33
  • 6