How to find the position of elements in a list satisfying criteria
Position[{2, 4, 6, 8, 10}, _?(# > 7 &)]
does the job. Apply Flatten[]
if need be.
As noted by Dan in a comment alluding to Brett's answer, using the level-specification argument of Position[]
might sometimes be needed, if the numbers are not Real
s, Rational
s or Integer
s.
As many have pointed out, Position
can be used for this, but you may want to take care since Position
will quite happily go into things you might not expect it to.
In[17]:= Position[Sin[{2, 4, 6, 8, 10}], _?(# > 0.5 &)]
Out[17]= {{1, 1}, {1}, {2, 1}, {3, 1}, {4, 1}, {4}, {5, 1}}
Note that we got match from the 4
in Sin[4]
being bigger than 0.5, even though numerically Sin[4]
around -0.75. We can use a level specification to limit the depth at which we're inspecting elements:
In[18]:= Position[Sin[{2, 4, 6, 8, 10}], _?(# > 0.5 &), 1]
Out[18]= {{1}, {4}}
Position
can take very generic patterns. Here we ask for the position of values in the list given that they are larger than 7.
x={2,4,6,8,10};
In[11]:= Position[x,val_/;val>7]
Out[11]= {{4},{5}}