Faran Baig
Faran Baig

Reputation: 3

Sorting function sort() does not work as expected in a specific case

I am pretty new to Python and am solving basic problem to learn my way into Python. In this process, I was trying out the sort() function to sort a list in the ascending order.

Increasing digits of the same numbers are sorted together even when they're not supposed to. For example, numbers 6, 66, 666 and so on are not supposed to be together if there is a number between them.

I have tried using different kinds of inputs, but everything gets grouped together like the following:

(base) C:\Data\Personal Data\Python>python test.py
10

1
11
111
1111
2
22
222
2222
3
33
['1', '11', '111', '1111', '2', '22', '222', '2222', '3', '33']

Following is the code written for this purpose:

t = int(input()) #Accepts user input for number of iterations
n = []

for i in range(t):
    u = input()
    n.append(u)

n.sort() 
print(n)

Although I haven't seen any error messages as such, the outputs are definitely what I expected them to be. Am I doing something wrong here?

Upvotes: 0

Views: 39

Answers (2)

Akash Pagar
Akash Pagar

Reputation: 637

Even you take input as numbers in string format in list, you can sort these using map and lambda function. Just use lambda function inside sort function.

n.sort(key=lambda x: int(x)) 

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

The problem is that you're sorting strings, not numbers, and the solution lies in your very code, just use int when reading all the numbers in the same way you're using it when reading the number of iterations:

for i in range(t):
    u = int(input())
    n.append(u)

Upvotes: 1

Related Questions