Here is given a nested list:

nl = [['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]]

Now I have to find the second lowest lists into the nested list by their second value. And append the second lowest lists into another list.

So the output should be:

['Harsh', 20], ['Beria', 20]

I wrote the following code but it doesn’t work:

nl = [['Harsh', 20], ['Beria', 20], ['Varun', 19], ['Kakunami', 19], ['Vikas', 21]] result=[] temp=max(nl, key=lambda x: x[1]) largest, larger = temp[1], temp[1] for num in nl: if num[1] < largest: largest, larger = num[1], largest elif num[1] < larger: larger = num[1] result.append(larger) print(result)

## Answer

Get the `min`

of the total elements, filter using that valid then get min of remaining and keep elements equal to min of remaining:

from operator import itemgetter # min of all elements mn = min(nl, key=itemgetter(1))[1] # remove elements equal to min filtered = [x for x in nl if x[1] != mn] # get min of remaining mn_fil = min(filtered,key=itemgetter(1))[1] # filter remaining out = [x for x in filtered if x[1] == mn_fil] print(out) [['Harsh', 20], ['Beria', 20]]

Works for both your cases:

In [19]: nl = [['Prashant', 32], ['Pallavi', 36], ['Dheeraj', 39], ['Shivam', 40]] In [20]: from operator import itemgetter In [21]: mn = min(nl, key=itemgetter(1))[1] In [22]: filtered = [x for x in nl if x[1] != mn] In [23]: mn_fil = min(filtered,key=itemgetter(1))[1] In [24]: out = [x for x in filtered if x[1] == mn_fil] In [25]: out Out[25]: [['Dheeraj', 36]]

Using a single for loop we remove all elements from the temp list if we find a lower element, if we find and equally lower one we append it:

mn = min(nl, key=itemgetter(1))[1] temp = [] best = float("inf") for ele in nl: if mn < ele[1] < best: best = ele[1] temp = [] out.append(ele) elif ele[1] == best: temp.append(ele) print(temp)