# How to find the second lowest lists into a nested list by their second value?

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)

largest, larger = temp, temp
for num in nl:
if num < largest:
largest, larger = num, largest
elif num < larger:
larger = num
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))

# remove elements equal to min
filtered = [x for x in nl if x != mn]

# get min of remaining
mn_fil = min(filtered,key=itemgetter(1))

# filter remaining
out = [x for x in filtered if x == mn_fil]
print(out)

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

Works for both your cases:

```In : nl = [['Prashant', 32], ['Pallavi', 36], ['Dheeraj', 39], ['Shivam', 40]]
In : from operator import itemgetter
In : mn = min(nl, key=itemgetter(1))
In : filtered = [x for x in nl if x != mn]
In : mn_fil = min(filtered,key=itemgetter(1))
In : out = [x for x in filtered if x == mn_fil]
In : out
Out: [['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))
temp = []
best = float("inf")
for ele in nl:
if mn < ele < best:
best = ele
temp = []
out.append(ele)
elif ele == best:
temp.append(ele)
print(temp)
```