get maximum number stored in a list

Question:

example #1

numbers = ['1086', '1123', '543', '1180', '1222', '1300', '888']
print(max(numbers))

result: 888,
desired result: 1300

example #2

numbers = ['1086', '1123', '1180', '1222', '1300']
print(max(numbers))

result: 1300,
desired result: 1300

goal

numbers = ['1086', '1123', '543', '1180', '1222', '1300', '888']
print(max(numbers))

result: 1300,
desired result: 1300

all 3 digit and 4 digit combinations should be involved

first 10 results from google index, that offering "enumarate", "max()", "sort()", [-1], [0] also different variations of "for" etc..
got me to write this question.
at most brain dead copy/paste.


numbers = ['888','999','543']
print(max(numbers))

output is the maximum value, if all of 3 items in a list are 3 digits long, but with 4 digits it acts like this.

what is this?

numbers = ['888','999','543','1000','999.9']
print(max(numbers))
if float(max(numbers)) < 1000:
    print("hello?")

max() function should be fixed.

Asked By: kvhrs

||

Answers:

Replace print(max(numbers)) with print(max(map(int, numbers)))

Answered By: Daniel

You list contains string not integers, you make use of map() to convert the string to integers:

numbers = ['1086', '1123', '543', '1180', '1222', '1300', '888']
print(max(map(int, numbers)))
>>> 1300
Answered By: Maurice Meyer

You could try to convert your string into integer like that:

numbers = ['1086', '1123', '543', '1180', '1222', '1300', '888']
print(str(max(map(int, numbers)))

I reconverted the result in string to have the same type as the initial list

Answered By: Till

Another solution would be to make use of the key parameter for max:

numbers = ['1086', '1123', '543', '1180', '1222', '1300', '888']
print(max(numbers, key=int))

Output:

1300
Answered By: B Remmelzwaal

One line generator with max() and int()

max(int(x) for x in numbers)

Or

max(numbers,key=int)
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.