Search code examples
pythonlistmin

Finding the minimum of a nested list that has a constant in element[1]


I have a nested list:

freqList = [[4, 2], [3, 2], [1, 1]]

And I want to find the minimum number in index[0] that has a constant (value) of 2 in index[1].

For this list elements 1 and 2 have a value of 2 at index[1] within the nested list therefore the 4 and 3 fit the criteria and the min number is 3 so the output should be 3

    for val in freqList:
        print(val[0])

Gives me the values in index[0] of the list but I'm not sure how to only print the values of index[0] that have a value of 2 in index[1] and then how to select the minimum.

Any ideas on how to do this?


Solution

  • If you want to get minimum of the first elements in the inner lists:

    min([val[0] for val in freqList])
    

    Also if you want to check inner lists for conditions:

    min([val[0] for val in freqList if CONDITION)
    

    which if your condition is val[1] == 2 (Also your question's answer)

    min([val[0] for val in freqList if val[1] == 2])
    

    or even you can check for multiple condition:

    min([val[0] for val in freqList if ((val[1] == 2) and (len(val) == 2))])