1
$\begingroup$

I have the following code:

Module[{lst},
    lst = {
        {1, 37, 2, 22},
        {3, 59, 9, 9},
        {6, 1, 32, 56},
        {31, 42, 46, 27},
        {58, 38, 64, 47}
    };
    FirstPosition[lst, x_ /; (x[[2]] == 42)]
    (* Also tried the following, with the same result *)
    (* FirstPosition[lst, _?(x[[2]] == 42 &)] *)
]

The code is simple enough, but I get the following error message before getting the right answer:

FirstPosition

Can you please help me find the error?

$\endgroup$

marked as duplicate by Mr.Wizard list-manipulation Mar 28 '17 at 23:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ Add the appropriate levelspec (or fix your pattern). Otherwise, your pattern matches more than you think. $\endgroup$ – ciao Mar 18 '15 at 7:32
  • $\begingroup$ @rasher Can you please provide the correct expression? FirstPosition[lst, x_ /; (x[[2]] == 42), 1, 1] returns the first line of the error message above. $\endgroup$ – Shredderroy Mar 18 '15 at 7:43
  • 2
    $\begingroup$ A simpler form that achieves the same result is FirstPosition[lst, 42][[1]] $\endgroup$ – Gordon Coale Mar 18 '15 at 8:41
  • 3
    $\begingroup$ FirstPosition[lst, x_ /; (Length[x]>=2 && x[[2]] == 42)], or FirstPosition[lst, x_List/; (x[[2]] == 42)] if it is safe to assume al expressions are lists that have a length of at least 2. $\endgroup$ – Michael E2 Mar 18 '15 at 10:09
  • 1
    $\begingroup$ It's not a bug, just a bit of a nuisance. You need to specify level 1 only, and no heads are to be checked. This first necessitates that you also provide a default value. FirstPosition[lst, x_ /; (x[[2]] == 42), Missing["IWasAPoorlyDesignedArgument"], {1}, Heads -> False] should do what you want $\endgroup$ – Daniel Lichtblau Mar 18 '15 at 15:38