I have wrong results with sorting function at python

Looks like your list is a list of strings and not a list of numbers. Is your list defined like this?

NumberList = ['9', '5', '13']

Update:

From your updated code snippet we see how you fill your list:

Number_list.append(raw_input())

You must know that in Python 2, raw_input returns the user input as string and does not parse it to a numeric type.

That means you are getting a list of strings, as I said. We can also see that you want to continue operating on numbers and not on strings, so it’s the easiest to just convert the input to integer numbers before appending them to the list:

Number_list.append(int(raw_input()))

That way we get a list of numbers and both the sorting and your calculations in the second half of your code will work as expected.


If we sort that list, it will sort the string content inside alphabetically according to the ASCII codes of the characters. And ‘1’ has of course a lower code than ‘5’ or ‘9’ and therefore ’13’ is the first element of the result.

You obviously want to sort the list numerically, so you need to either directly fill the list with numbers which was probably intended, or if there’s a special reason why the list has to be filled with strings, you need to specify a key function that converts the elements to numbers.

  • Option 1 (list of numbers):

    Number_list = [9, 5, 13]
    Number_list.sort()
    print Number_list
    # output: [5, 9, 13]
    
  • Option 2 (list of strings, but with sort key):

    Number_list = ['9', '5', '13']
    Number_list.sort(key=int)
    print Number_list
    # output: ['5', '9', '13']
    

Leave a Comment