-1
$\begingroup$

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.

$\endgroup$

closed as off-topic by chuy, ciao, m_goldberg, MarcoB, Oleksandr R. Jul 30 '15 at 23:43

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – chuy, ciao, m_goldberg, MarcoB, Oleksandr R.
If this question can be reworded to fit the rules in the help center, please edit the question.

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

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

$\endgroup$

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