How to handle Part function error when position does not exist?
But what if I wish to handle that error. So in this case, I want to return empty list {} if the part-does-not-exist error happens
One possibility might be
ClearAll[process];
process[lis_List, (n_Integer)?Positive] := Module[{},
Quiet@Check[lis[[n]], {}, Part::partw]
]
Or just
process[lis_List, (n_Integer)?Positive] := Quiet@Check[lis[[n]], {}, Part::partw]
And now
list = {{1, 2}, {3, 4}};
process[list, 2]
(*{3, 4}*)
and
process[list, 3]
(* {} *)
Quiet
can be removed if you want to hear the beep and see the error message on console.
As with the essence of @Nasser's answer, I go with a simplified version for now.
Quiet[Check[{{1, 2}, {3, 4}}[[3]], {}], Part::partw]
This returns empty list if partw message happens.
Have you considered Query
? Default behavior:
list = {{1, 2}, {3, 4}}
Query[3][list]
Missing["PartAbsent", 3]
Somewhat customized:
fn = Replace[Missing["PartAbsent", _] -> {}];
Query[3, fn][list]
{}
Or with care:
Unprotect[Missing];
Missing["PartAbsent", _] = {};
Protect[Missing];
Query[3][list]
{}
Caveat, Query
can be slow:
- Why is Query so much slower than Part?