Search code examples
pythonpython-3.xlist-manipulation

Find sublist of second largest elements in a list (Python 3)


Given a list:

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]

What is a simple way to extract the second-largest elements?

[44, 44, 44]

My attempt

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]
def sublist_of_second_largest(lis):
    maxx=max(lis)
    n=lis.count(maxx)
    for i in range(n):
        lis.remove(maxx)
    maxx=max(lis)
    n=lis.count(maxx)
    out=[]
    for i in range(n):
        out.append(maxx)
    return out

print(sublist_of_second_largest(lis))

Solution

  • While Zain's answer is correct and consice, due to the sorting it has an O(n log n) runtime. This might not matter to you, but if it does here is an O(n) implementation:

    def sublist_of_second_largest(num_lst):
        num_set = set(num_lst)
        num_set.remove(max(num_set))
        snd_largest_num = max(num_set)
        return [val for val in num_lst if val == snd_largest_num]
    
    print(sublist_of_second_largest([37.21, 37.21, 37.2, 44, 44, 44, 101, 101]))
    

    Prints:

    [44, 44, 44]