How to find the largest number(s) in a list of elements, possibly non-unique?

Just get the maximum using max and then its count and combine the two in a list-comprehension.

item_no = [5, 6, 7, 8, 8]

max_no = max(item_no)
highest = [max_no for _ in range(item_no.count(max_no))]
print(highest)  # -> [8, 8]

Note that this will return a list of a single item in case your maximum value appears only once.


A solution closer to your current programming style would be the following:

item_no = [5, 6, 7, 8, 8]
max_no = 0  # Note 1 
for i in item_no:
    if i > max_no:
        max_no = i
        high = [i]
    elif i == max_no:
        high.append(i)

with the same results as above of course.

Notes

  1. I am assuming that you are dealing with N* (1, 2, ...) numbers only. If that is not the case, initializing with -math.inf should be used instead.

Note that the second code snippet is less efficient than the first by quite a margin. Python allows you to be more efficient than these explicit, fortran-like loops and it is more efficient itself when you use it properly.


You can do it even shorter:

item_no = [5, 6, 7, 8, 8]
#compute once - use many times
max_item = max(item_no)
print(item_no.count(max_item) * [max_item])

Output:

[8, 8]

You could use list comprehension for that task following way:

numbers = [5, 6, 7, 8, 8]
maxnumbers = [i for i in numbers if i==max(numbers)]
print(*maxnumbers,sep=',')

output:

8,8

* operator in print is used to unpack values, sep is used to inform print what seperator to use: , in this case.

EDIT: If you want to get indices of biggest value and call max only once then do:

numbers = [5, 6, 7, 8, 8]
biggest = max(numbers)
positions = [inx for inx,i in enumerate(numbers) if i==biggest]
print(*positions,sep=',')

Output:

3,4

As you might check numbers[3] is equal to biggest and numbers[4] is equal to biggest.