user8178930
user8178930

Reputation:

How to get all the highest integers in a list in Python

I have a list:

numbers = [1, 2, 3, 4, 5, 5, 2, 3]

Now I know how to get the highest integer:

max(numbers)

But this would only get 5. What I want it the two 5s in the list. Is there a way of getting all the highest integers in the list?

Upvotes: 1

Views: 78

Answers (3)

Chen A.
Chen A.

Reputation: 11280

You can use max to get the highest value, and then count on the list to get number of occurrences

m = max(numbers)
numbers.count(m)
res = [m] * numbers.count(m)
# [5, 5]

Upvotes: 2

user2340612
user2340612

Reputation: 10703

If you want a list containing only the highest number:

maximum = max(numbers)
highest = list(filter(lambda x: x == maximum, numbers))

Upvotes: 1

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

You can use a list comprehension:

max_num = max(numbers)
highest = [num for num in numbers if num == max_num]

Upvotes: 8

Related Questions