0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.