Being a novice, I'm having trouble with the following: I have a list of lists and want only those elements where the second element of the second level is positive. So, for example, from


I want to get


I know that it has to be easy, but I've tried


I've tried setting list2={{},{}} and then


and a few things that I've forgotten. I know that it has to be easy but I've spent an hour on it and am out of patience!

  • $\begingroup$ Select[list1, #[[2]] > 0 &] $\endgroup$ – BlacKow Mar 8 '17 at 22:04
  • $\begingroup$ Just that easy. Thanks! If you (or anyone) has a moment, I'd like to understand why my first attempt, i.e., Select[list1,list1[[1,2]]>0, fails. $\endgroup$ – Rob Mar 8 '17 at 22:09
  • $\begingroup$ Just for fun: Pick[#, UnitStep@#[[All, 2]], 1] &@list1 $\endgroup$ – user1066 Mar 8 '17 at 22:35
  • 1
    $\begingroup$ Also Select[Last /* Positive] @ list1 $\endgroup$ – Simon Woods Mar 8 '17 at 22:56

A bit too long for a comment. Your first attempt Select[list1,list1[[1,2]]>0] (I assumed that there is closing bracket in the end) doesn't fail, it does a different thing though. Select takes a boolean function for its second argument. This function is being applied to all elements of your list and if evaluates as True the element is selected. When you plugged list[[1,2]]>0 in place of that test function you get always False because your list1[[1,2]] equals $-1$. The Select[list1, #[[2]] > 0 &] has a pure function in the second place. The #[[2]] > 0 & means following: check if second element of your argument is greater than $0$.

Regarding For loop attempt, don't even try to use For, here is why.

| improve this answer | |
  • 1
    $\begingroup$ in addition to @BlacKow 's answer I would like to say that you can use Pick[list1, Thread[list1[[All, 2]] > 0], True] if you want to operate the boolean logic on the list prior to selecting the elements $\endgroup$ – Ali Hashmi Mar 8 '17 at 22:27
  • $\begingroup$ Thank you BlacKow and Al Hashmi, greatly appreciated. $\endgroup$ – Rob Mar 8 '17 at 22:32
  • 2
    $\begingroup$ @Rob - while we're listing equivalent ways to do it, my first thought would be something like Cases[list1, {_, a_ /; a > 0}] $\endgroup$ – Jason B. Mar 8 '17 at 22:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.