1
$\begingroup$

Is there a Mathematica function or some simple expression that can be used to judge if a part is within or beyond a list? For example, list={100,200,300,400}. The desired expression with the argument list[[4]] would give True, but False for the argument List[[6]]. I can think of getting Length[list] and compare it with the index, but is there a better way to do that?

$\endgroup$
1
$\begingroup$

If your list contains numbers you can use

Quiet@NumericQ@list[[6]]

False

or

Quiet@Check[list[[6]],False]

False

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ Also Quiet[Check[list[[6]], False]] $\endgroup$ – Chris Degnen Apr 4 '19 at 21:32
  • $\begingroup$ The list does not have to be integers. Also, it is generally better to use NumericQ rather than NumberQ since NumericQ also recognizes numeric constants such as E or Pi. $\endgroup$ – Bob Hanlon Apr 4 '19 at 22:01
  • $\begingroup$ yes numeric is better, I didn't say that the list must be integers. That's why I said "if". The second code is more general $\endgroup$ – J42161217 Apr 4 '19 at 22:06
1
$\begingroup$

The function you ask for doesn't sound very useful. It is probably easier to just check the argument of the Part function. But here at least something that fills the requirement as I understand it:

list = Range[5]
(* {1, 2, 3, 4, 5} *)

ClearAll[LegallyIndexedQ]
LegallyIndexedQ[HoldPattern[Part[x_, n_]]] := (Abs[n] <= Length[x]) && n ∈ Integers
SetAttributes[LegallyIndexedQ, HoldFirst]

LegallyIndexedQ[list[[5]]]
(* True *)

LegallyIndexedQ[list[[6]]]
(* False *)

LegallyIndexedQ[list[[0]]]
(* True *)

LegallyIndexedQ[list[[1.5]]]
(* False *)
|improve this answer|||||
$\endgroup$
1
$\begingroup$

This function tests if there exists in a expression exp a part at position pos = {i1,i2,...}.

myPartExistQ[exp_, pos_] := Module[{flag},
  flag = False;
  ReplacePart[exp, {pos} :> (flag = True)];
  flag]  


myPartExistQ[{1, 2, 3, 4, 5}, {6}]
myPartExistQ[{1, 2, 3, 4, 5}, {1, 1}]  

False
False

There are to cases of invalid position when using Part: Either the length of a sub-expression is too short, or the path specified by the position hits a atomic object.

myPartExistQ handles both cases.

It works with ragged array of arbitrary depth.

|improve this answer|||||
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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