Anshika Singh
Anshika Singh

Reputation: 1044

How to sort user input list elements?

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]

Upvotes: 1

Views: 5908

Answers (4)

bhavesh
bhavesh

Reputation: 1

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

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

Upvotes: 0

Ege Yıldırım
Ege Yıldırım

Reputation: 435

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

Upvotes: 0

Selcuk
Selcuk

Reputation: 59228

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(",")]

Upvotes: 1

zack256
zack256

Reputation: 171

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

Upvotes: 2

Related Questions