2

I am having an issue with my input method, I am trying to get a list of ints seperated by spaces. My code is below:

def numberStore():
    numberList = input("Enter list of numbers seperated by spaces ").split(" ")
    print("The lowest number is" , listLowestNumber(numberList))

I then have a function to return the lowest number of the list that has been input.

def listLowestNumber(list):
    list.sort()
    return list[0]

However when I execute the function numberStore, it only seems to sort the numbers by the first digit, for example entering the values 40 9 50 will return a value of 40 as the lowest number. Thanks for any help!

1
  • 3
    min(the_list, key=int) is what you want Commented Mar 16, 2013 at 22:49

3 Answers 3

3

To sort a list of integers represented as strings, one could use:

l.sort(key=int)

Without the key=int, the list gets ordered lexicographically.

However, if all you need to do is find the smallest number, the better way is

return min(l, key=int)

P.S. I've renamed your list to l since list() is a built-in name, and it's poor style to shadow built-in names.

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

Comments

1

You need to convert values on your list to int before you sort them:

numberList = input("Enter list of numbers seperated by spaces ").split()
numberList = [int(v) for v in numberList]

Comments

0

Looks like it's sorting by treating the elements as strings. What you describe is lexicographic ordering, not numerical ordering. Basically you have to convert your string elements into numerical elements.

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.