4
$\begingroup$

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

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

3 Answers 3

7
$\begingroup$
 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.

$\endgroup$
8
  • $\begingroup$ I just realized that I misunderstood the question. Oops. $\endgroup$
    – Mr.Wizard
    Commented Jan 14, 2013 at 13:23
  • $\begingroup$ 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. $\endgroup$
    – Mr.Wizard
    Commented Jan 14, 2013 at 13:31
  • $\begingroup$ @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. $\endgroup$
    – Ed Mendes
    Commented Jan 14, 2013 at 13:32
  • $\begingroup$ @EdMendes, excellent point.. will fix in a moment. $\endgroup$
    – kglr
    Commented Jan 14, 2013 at 13:38
  • 1
    $\begingroup$ @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. $\endgroup$
    – kglr
    Commented Jan 14, 2013 at 13:52
7
$\begingroup$

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}.

$\endgroup$
1
  • $\begingroup$ Wizard - Many thanks. It does not seem to work with a list such as {k,2k,a} though. $\endgroup$
    – Ed Mendes
    Commented Jan 14, 2013 at 12:50
1
$\begingroup$

Using SequencePosition (introduced in 2015 with V 10.1)

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

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

gives

3
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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