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]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
Anshika Singh
  • 994
  • 12
  • 20

4 Answers4

2

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

zack256
  • 181
  • 1
  • 5
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(",")]
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Yes this works! Can you provide me some details on p.sort(**key=int**), some link or so? – Anshika Singh Jun 24 '20 at 06:31
  • I suggest you to read the [official docs](https://docs.python.org/3/howto/sorting.html#key-functions) first. This [answer](https://stackoverflow.com/a/3426120/2011147) (which happens to be a duplicate of your question) might help as well. – Selcuk Jun 24 '20 at 07:11
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

Ege Yıldırım
  • 430
  • 3
  • 14
0
a = input()
p = a.split(',')
p.sort(key=int)
print(p)

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