+ 4

Why is Max() method not returning the larger value?

numbers = '1 2 4 67 123 146 1024 1982'.split() print(max(numbers))

2nd Nov 2021, 12:54 PM
Oral Napier
3 Antworten
+ 8
Martial Law , after splitting the input string, the elements of list 'numbers' are still strings. so the element starting with the highest digit will be returned by the max() function. if you wanted to make the elements of the list as int numbers, you can use map() function: numbers = list(map(int, '1 2 4 67 123 146 1024 1982'.split()))
2nd Nov 2021, 1:10 PM
Lothar
Lothar - avatar
+ 1
It returning 67 which is larger according to alphabetical order. 'numbers' there is a list of string type so it will work on sorting by lexicographical order.
2nd Nov 2021, 1:11 PM
Jayakrishna 🇮🇳
+ 1
Hi Martial! The reason it's not returning the largest value is because split() method returns list of strings not integers. You may try this print(numbers) You can use key (optional argument of max() )to compare the items by their integer value. print(max(numbers, key = int)) Output: 1982
2nd Nov 2021, 1:22 PM
Python Learner
Python Learner - avatar