Max() function: Wrong output

Hello guys,
I’m trying the max function in Python 3.10 to select the highest value in a user-defined list but i’m getting the wrong result repetitively as follows:

numbers=input(“Enter 5 numbers separated by comma:”)
print(“The list of user-input values is:”,list)
highest=max(list) #max is a builtin function
print(“The highest value in the list is:”,highest)


Am I missing sthg here?


Hello, @PythonGuy.
“Input” returns a string, even you split it into ‘numbers’. And, because of that, max() function can’t do what it normally does -because it works with numeric values like integers-. To simply solve this problem, you can use a for loop, or a for-shorthand as below:

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

I hope, this will help you.

1 Like

Thank you for posting your code as text. In future, you can format it as code using the </> button in the editor, or if posting from email, you can surround it using triple backticks:

code goes here

or just by indenting it.

Because you have posted the output as an image, I can’t see it, so I have to guess what the problem is.

You have a list of strings, not ints. Just because you tell the user to enter numbers, doesn’t mean that they do. And even if they type in digits, they are just strings of digits, not numbers.

Strings are compared in lexicographical order, not numeric order.

So "9" > "10000" (strings) even though 9 < 10000 (ints).

You need to convert the strings to ints. One way you can do that is with a list comprehension:

# Don't use the builtin name "list" as your own variable,
# it will cause trouble later on.
mylist = numbers.split(",")
mylist = [int(s) for s in mylist]

Another way is with the map builtin:

mylist = numbers.split(",")
mylist = list(map(int, mylist))

It is a matter of personal taste which is better.

Thanks. It worked.

The bizarre thing here is that I’m just learning from a python book and what I coded was written in the book in exactly the same format!

Unless that section was talking about the trap of thinking strings are automatically converted to numbers, you should find a different book.

1 Like

Which book?

What does it say?

There is nothing wrong with using max() on a list of strings, so long as you understand that it returns the greatest string in lexicographical order, not numeric order.