Returning only the highest value of a Python list

Asked

Viewed 26,379 times

2

I have the list ['4', '07', '08', '2017', '364', '355673087875675'] and would like to re a formula to return the higher value, which in this case would be the '355673087875675', tried to use the max(), but it didn’t work, I’m not being able to think of a simple solution to this problem, I’m thinking of using a sorting algorithm but it would be too big the code, there must be some way to do it.

2 answers

7


Use int as the sort function for the max function

>>> l = ['4', '07', '08', '2017', '364', '355673087875675']
>>> max(l, key=int)
'355673087875675'

2

Has. Use the function itself max. The problem why your code didn’t work is because you have a list of strings and you want to evaluate them as integer values, so you need the conversion.

numbers = ['4', '07', '08', '2017', '364', '355673087875675']

print(max(int(number) for number in numbers))  # 355673087875675

See working on Ideone | Repl.it

That is, instead of applying max right in the list, you need to apply it to a list whose all values have been properly converted to integer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.