Filter list of lists in Python by element value

Suppose I have a list lines where every element is a list

['2015', 'Friday', 9.94, 0.0]
['2015', 'Tuesday', 10.54, 0.002615]
['2015', 'Wednesday', 9.86, -0.001531]
['2016', 'Monday', 10.41, 0.007841]
['2016', 'Thursday', 11.51, 0.006415]
['2017', 'Tuesday', 8.74, -0.003711]
['2017', 'Friday', 12.62, 0.008516]

How would I filter out the list if, for example, I wanted to get all the elements where the first element of a list is 2016 and the second element is Monday? Think of this as filtering out a pandas dataframe by column values, but using a list of lists.

>Solution :

Just use a list comprehension with condition:

>>> [x for x in lst if x[0] == 2016 and x[1] == "Monday"]
[[2016, 'Monday', 10.41, 0.007841]]

Leave a Reply