-1

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))
dstrants
  • 7,423
  • 2
  • 19
  • 27
conor
  • 1,131
  • 1
  • 15
  • 20
  • 2
    Always try to use snake_case when naming variables and functions. see [PEP8](https://www.python.org/dev/peps/pep-0008/) – Zain Arshad Jun 13 '20 at 12:43

2 Answers2

3

Simple pythonic way:

lis = [37.21, 37.21, 37.2, 44, 44, 44, 101, 101]
num = sorted(set(lis), reverse=True)[1]
print([i for i in lis if i == num])

Ouput:

[44, 44, 44]

Zain Arshad
  • 1,885
  • 1
  • 11
  • 26
1

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]
shmulvad
  • 636
  • 4
  • 15