Eyad H. Eyad H. - 5 months ago 10
Python Question

Why is sort() not working properly?

I am supposed to write a code that initializes an empty list, then read commands and apply them to this list. Everything I have written so far is working great except for sort(), the list was ['5', '10', '9', '1'] and it became ['1', '10', '5', '9'] after sorting which obviously isn't right.
That's my code:

N = int(input()) ## number of commands
L = []
for i in range(N):
userInput = input().split()
cmd = userInput[0]
args = userInput[1:]
if cmd == "insert":
L.insert(int(args[0]), args[1])
elif cmd == "print":
print(L)
elif cmd == "remove":
L.remove(args[0])
elif cmd == "append":
L.append(args[0])
elif cmd == "sort":
L.sort() ## the only method that doesn't work properly.
elif cmd == "pop":
L.pop()
elif cmd == "reverse":
L.reverse()

Answer

You're doing a string sort on the input list (which is made up of strings representing numbers). Hence a lexicographic sort is performed, and that means that 10 comes after 1 but before 5 (it's the same order words would appear in a dictionary). To get the desired order with the expected data type, try this:

L.sort(key=int)

In the above code we use the integer representation of each element in the list as a key, therefore sorting the list according to the correct order.

Another valid possibility would be to always work with a list of integers (in case you didn't intend the input to be a list of strings). If that makes more sense, modify the following cases to make sure that you handle the right data type:

if cmd == "insert":
    L.insert(int(args[0]), int(args[1]))
elif cmd == "remove":
    L.remove(int(args[0]))
elif cmd == "append":
    L.append(int(args[0]))