# How to get a 'False' when judging if a part is beyond a list?

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?

If your list contains numbers you can use

Quiet@NumericQ@list[[6]]


False

or

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


False

• Also Quiet[Check[list[[6]], False]] Apr 4 '19 at 21:32
• 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. Apr 4 '19 at 22:01
• 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 Apr 4 '19 at 22:06

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


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.