1

I am trying to get a list input by the user and then sort the list elements (which are integers) in ascending order. But the elements are stored as strings and I don't know how to convert each element into int type. For example:

p = input("Enter comma separated numbers:")
p = p.split(",")
p.sort()
print(p)

When I input

-9,-3,-1,-100,-4

I get the result as:

['-1', '-100', '-3', '-4', '-9']

But the desired output is:

[-100, -9, -4, -3, -1]
0

4 Answers 4

2

Try p = list(map(int, p.split(","))) instead of your second line, does that work?

Sign up to request clarification or add additional context in comments.

Comments

1

Your p is a list that consists of strings therefore they won't be sorted by their numerical values. Try this:

p.sort(key=int)

If you need a list of integers, convert them in the beginning:

p = [int(i) for i in p.split(",")]

2 Comments

Yes this works! Can you provide me some details on p.sort(key=int), some link or so?
I suggest you to read the official docs first. This answer (which happens to be a duplicate of your question) might help as well.
0

input("blabla") returns string values even if you are inputting numbers. When you are sorting p, you are not sorting integers like you think.

This piece of code converts string elements of a list to integers, you can do this first then sort the new integer array:

 for i in range(0,len(p)):
        p[i] = int(p[i])

or in easier way you can turn string elements to integers while splitting the string by using int parameter, as zack256 mentioned above

Comments

0
a = input()
p = a.split(',')
p.sort(key=int)
print(p)

a = input("type--")
p = list(a.split(','))
p.reverse()
print(p)

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.