5

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

list1={{1,-1},{12,4},{8,-6},{2,2},{3,-1},{4,4}} 

I want to get

list2={{12,4},{2,2},{4,4}}

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

list2=Select[list1,list1[[1,2]]]>0

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

For[j=1,j<=Length[list1],j++,If[list1[[j,2]]>0,Append[list2,list1[[j]]]]]

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!

Stitch
  • 4,205
  • 1
  • 12
  • 28
Rob
  • 141
  • 1
  • 2

1 Answers1

9

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.

BlacKow
  • 6,428
  • 18
  • 32
  • 1
    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 – Ali Hashmi Mar 08 '17 at 22:27
  • Thank you BlacKow and Al Hashmi, greatly appreciated. – Rob Mar 08 '17 at 22:32
  • 2
    @Rob - while we're listing equivalent ways to do it, my first thought would be something like Cases[list1, {_, a_ /; a > 0}] – Jason B. Mar 08 '17 at 22:35