# Picking elements from a list

That's must be a very trivial question. Suppose we have the simple list

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};


Then, is there a quick and elegant way to pick the element with non-zero and positive y value? In this example, we should get {0.2, 0.4}.

• Select[data, Positive[#[[2]]]&] Commented Jun 27, 2019 at 14:36
• Alternatively, data//Pick[#, Sign[#[[All,2]]],1]& Commented Jun 27, 2019 at 15:50
• A minor variation: Select[Positive@*Last][data]
– Syed
Commented Feb 4 at 2:07

Select is a good option here. Jason has shown in the comments how to use the Positive function. If you want a bit more flexibility for future usage, you can use a standard greater than operator.

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};
positivedata=Select[data, #[[2]] > 0 &]


You can also use Cases:

Cases[{_, _?Positive}] @ data


{{0.2, 0.4}}

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};


Pre-define pattern for better comparability

p = {_, x_} /; x <= 0;


Using SequenceSplit (new in 11.3)

First @ SequenceSplit[data, {p}]


{{0.2, 0.4}}

Using ReplaceAt (new in 13.1)

ReplaceAt[data, _ :> Nothing, Position[p] @ data]


{{0.2, 0.4}}

Using ReplaceAll

data /. p :> Nothing


{{0.2, 0.4}}

Using Delete

Delete[Position[p] @ data] @ data


{{0.2, 0.4}}

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}, {-1, -1}};


Using Pick:

Pick[#, Element[#, PositiveReals] & /@ #] &@data

(*{{0.2, 0.4}}*)


Or using DeleteCases:

DeleteCases[data, s_ /; ! MatchQ[Sign@s, {1 ..}]]

(*{{0.2, 0.4}}*)


An alternative using Pick:

Pick[#, MatchQ[Thread[{##} > 0], {True ..}] & @@@ #] &@data

(*{{0.2, 0.4}}*)

• I know it works for this case but if data have {-1,-1}, then your approach will not work. Commented Feb 4 at 1:07
• Thanks for the observation, @OkkesDulgerci! See the update, please. :-) Commented Feb 4 at 1:18

A Reap/Sow variant:

Reap[Sow @@@ data, _?(# > 0 &), {#2[[1]], #1} &][[2]]

data = {{-1, 0}, {0.2, 0.4}, {4, 0}, {0.3, 0}, {0.2, -0.4}};

Select[0 < ArcTan @@ # < π &][data]


{{0.2, 0.4}}

Visualization:

pts = RandomReal[{-1, 1}, {400, 2}];
sel = Select[0 < ArcTan @@ # < π &][pts];
unsel = Complement[pts, sel];
ListPlot[{sel, unsel}, PlotStyle -> {Red, Blue}]