user10332687
user10332687

Reputation:

Get max number out of strings

I have the following 'numbers', which are actually strings from a regex:

nums = ['1', '4', '9', '10']

I would like to get the max, which would be 10. Is there a cleaner way to do this than to do a list comprehension, such as:

>>> max(nums)
'9'
>>> max([int(item) for item in nums])
10

Otherwise, it would give me 9.

Upvotes: 1

Views: 74

Answers (2)

Adam Smith
Adam Smith

Reputation: 54163

max has a keyword argument key that takes a callable which transforms the values in some way before comparing them.

>>> max(nums, key=int)

This is essentially the same as your list comprehension max(int(item) for item in nums), except that it's important to note that the original values are returned, not the transformed values. This means that:

>>> a = max(nums, key=int)
>>> b = max(int(item) for item in nums)
>>> repr(a), repr(b)
('10', 10)

Upvotes: 11

Tim
Tim

Reputation: 2843

Use the map function:

>>> max(map(int, nums))

Upvotes: 1

Related Questions