# Position not working? [closed]

I have the list:

myList={0,0,0,a,b,c,0,0,d}


I need to find the positions of all elements that are non-zero. I do like this:

Position[myList,x_ /; x != 0]


The output is {}. Meanwhile, the output for:

In= Position[myList,x_ /; x == 0]
Out= {{1}, {2}, {3}, {7}, {8}}


I don't understand what is going on. a,b,c and d are symbolic variables.

• Position[myList,Except, {1}, Heads -> False] – george2079 Jul 30 '15 at 20:16
• check out a != 0 Does this return True? – chuy Jul 30 '15 at 20:16
• All work, thank you! – space_voyager Jul 30 '15 at 20:25

This is indeed somewhat confusing when you are new to Mathematica.

In Mathematica, == stands for mathematical equality. Thus a == 0 does not evaluate to either True or to False until a is replaced by a numerical value. a is considered to be a variable that may or may not be zero.

A pattern like x_ /; condition will only match if condition is explicitly True. Anything else than True, including things that are not literally False, will cause the match to fail.

So what can you do here?

You can use === which tests if two expressions are structurally the same. But note that 0 === 0. is False, as these two values are not identical (even if mathematically they're the same). With === you'd have to separately test for both 0 and 0., which is inconvenient and error prone. The same goes for Except.

Here I would rely on TrueQ, which can turn things that are not literally the symbol True into False.

Position[myList, x_ /; Not@TrueQ[x == 0], {1}, Heads -> False]


Additionally I used a level specification to look only at the first level, and asked not to test the head (which is List).