9
$\begingroup$

Here is a simple list:

l={1, 0, 2, 1, 0, 1, 0, 1, 2, 0, 2, 0, 1, 0, 1, 0, 0}

To get the position of non-zero elements I use Position with Except:

Position[l,Except[0]]

Mathematica 9.0.1 returns

{{0}, {1}, {3}, {4}, {6}, {8}, {9}, {11}, {13}, {15}, {}}

I can't figure out why the first element is {0} and the last one is {}. If I use Cases it works as expected:

Cases[l,Except[0]]

{1, 2, 1, 1, 1, 2, 2, 1, 1}

What am I missing here?

$\endgroup$
13
$\begingroup$

The {0} represents the head of the expression. For example,

l[[0]]

(* ==> List *)

About {}, the docs say

A part specification {} returned by Position represents the whole of expr.

You get these results because Position searches the expression at all levels. To get what you were looking for, use

Position[l, Except[0], {1}, Heads -> False]

to search only at level 1 and to ignore heads.


To see what the results returned by Position mean, you can use Extract. Extract supports all part specifications returned by Position, including {}:

Mathematica graphics

$\endgroup$
  • 8
    $\begingroup$ It may be worth adding that the traversal is depth-first, head before elements, but the entire expression is considered last, not first. This would explain the ordering of the results. $\endgroup$ – Leonid Shifrin Mar 20 '13 at 15:01
  • $\begingroup$ Thanks for answering so quickly. $\endgroup$ – jerome Mar 20 '13 at 15:18
  • $\begingroup$ Or, perhaps, Position[l, Except[0, _?NumericQ]] == Position[l, Except[0, _Integer]] $\endgroup$ – user1066 Mar 20 '13 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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