6
$\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
  • 9
    $\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
  • 2
    $\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

5 Answers 5

11
$\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$
3
$\begingroup$
list = {1, 2, 3, 4, 5, 6 p6, 7 p7, 8, 9};

Using SequencePosition

List@*First /@ SequencePosition[list, {Except[_?NumberQ]}]

{{6}, {7}}

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

Using Cases:

rule = Rule[a_, b_] /; ! NumericQ[b] :> {a};

Cases[Thread @@ {Range@Length@# -> #} &@list, rule]

(*{{6}, {7}}*)
$\endgroup$
2
$\begingroup$

Using MapIndexed and Pick:

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

Pick[##, False] & @@ Thread[MapIndexed[{#2, NumberQ[#1]} &, lst]]

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

Using SequenceSplit (new in 11.3)

p = Alternatives @@ First @ SequenceSplit[list, {_?NumberQ}]

6 p6 | 7 p7

Position[list, p]

{{6}, {7}}

$\endgroup$

Your Answer

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

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