# How find the first element of a list greater than zero (or another criterion) when there is a symbol in the list?

I need to find the position of the first element of a list that is either greater than zero (or some other criterion) or a symbol.

Something like

 lst={0,0,k,1,4}


and as result

 position = 3


If there was no symbol the following command would do the job

 First[Flatten[Position[lst, _?(Abs[#] > 0 &)]]]


If I add || MatchQ[_Symbol] the answer will always be zero.

Many thanks

• How about First[Flatten[Position[lst, _?(NumericQ[#] && Abs[#] > 0 &)]]] ? Commented Jan 14, 2013 at 12:29

 Position[lst, Except[0|0., _], {0, Infinity}, 1, Heads -> False][[1,1]]


or

 Cases[lst, {zeros : (0|0.) ..., Except[0|0.], ___} :> 1 + Length[{zeros}], {0}][[1]]


or

 Length@First@Split[lst, #1 == 0 &]


or

 1 + LengthWhile[lst, # == 0 &]


all give 3.

• I just realized that I misunderstood the question. Oops. Commented Jan 14, 2013 at 13:23
• I'm a bit confused by your code. Why are you looking at levels down to Infinity in the first line? Why are you assuming that the only non-negative numbers are 0? Maybe I still don't understand the question. Commented Jan 14, 2013 at 13:31
• @kguler - Many thanks, however there is a problem if one has 0. instead of 0 for the first two options. Third works great. Many thanks. Commented Jan 14, 2013 at 13:32
• @EdMendes, excellent point.. will fix in a moment.
– kglr
Commented Jan 14, 2013 at 13:38
• @Mr.W, {0,Inifinity} is my "instinctive default" levelspec ; it is not necessary in this case, 1 or {1} sufficient. Regarding "the only non-negative numbers..", I was going with the condition _?(Abs[#] > 0 &) in Ed's code.
– kglr
Commented Jan 14, 2013 at 13:52

I misread the question. Assuming I now understand you just want:

lst = {0, 0, k, 1, 4}

Position[lst, _?Positive | _Symbol, 1, 1, Heads -> False][[1, 1]]

3


My misreading was itself an interesting problem. I thought you wanted the position of the first positive value as if the symbols were not in the list. For example:

lst = {b, 0, k, 0, 1, 4}

Position[
Cases[lst, _?NumericQ],
_?Positive, 1, 1
][[1, 1]]

3


because 1 is at position three in {0, 0, 1, 4}.

• Wizard - Many thanks. It does not seem to work with a list such as {k,2k,a} though. Commented Jan 14, 2013 at 12:50

Using SequencePosition (introduced in 2015 with V 10.1)

list = {0, 0, k, 1, 4};

SequencePosition[list, {0, Except[0]}][[1, 2]]


gives

3