2
$\begingroup$

If I have a list containing both numbers and non-numbers, such as

{1,2,3,4,5,6p6,7p7,8,9}

how do I locate the positions in the list which do not contain numbers. So for the above example, I am looking for the output {{6},{7}}. I want to use the position command, but I don't know what pattern to specify.

Thanks in advance for any help.

$\endgroup$
4
  • 8
    $\begingroup$ Position[{1,2,3,4,5,6 p6,7 p7,8,9}, Except[_?NumberQ], {1}, Heads -> False] ? $\endgroup$
    – Ben Izd
    Mar 21, 2022 at 14:53
  • 2
    $\begingroup$ Something like Rest@Position[l, Except[_Integer], {1}]? $\endgroup$
    – Carl Lange
    Mar 21, 2022 at 14:53
  • 1
    $\begingroup$ Ah, yes, Heads -> False is much better than Rest. Ben's answer is much more idiomatic than mine. $\endgroup$
    – Carl Lange
    Mar 21, 2022 at 14:54
  • 1
    $\begingroup$ another option not using Position is MapIndexed[If[Not[NumericQ[lis[[First[#2]]]]], #2, Nothing] &, lis] gives {{6}, {7}} $\endgroup$
    – Nasser
    Mar 21, 2022 at 18:39

1 Answer 1

6
$\begingroup$
list = {1, 2, 3, 4, 5, 6 p6, 7 p7, 8, 9};

All of the following

Position[list, _?(Not@*NumericQ), {1}, Heads -> False]

Position[list, Except[_?NumericQ], {1}, Heads -> False]

Position[Map[NumericQ, list, {1}], False]

return

{{6}, {7}}


Note also that the above work for more complicated structures like the one

list = {{1, 2, 3}, {4, 5, 6 p6}, {7 p7, 8}, 9};

with a minimal modification

Position[list, _?(Not@*NumericQ), {2}, Heads -> False]

Position[list, Except[_?NumericQ], {2}, Heads -> False]

Position[Map[NumericQ, list, {2}], False]

give back

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

$\endgroup$

Your Answer

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

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