Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 10 down vote accepted

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

share|improve this answer
    
+1. That was really fast, by the way. –  Leonid Shifrin Mar 20 '13 at 14:58
6  
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. –  Leonid Shifrin Mar 20 '13 at 15:01
    
Thanks for answering so quickly. –  Jerome Mar 20 '13 at 15:18
    
Or, perhaps, Position[l, Except[0, _?NumericQ]] == Position[l, Except[0, _Integer]] –  TomD Mar 20 '13 at 18:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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