Function Repository Resource:

PositionQ

Source Notebook

Check if a list of indices is a valid position in an expression

Contributed by: Sjoerd Smit

ResourceFunction["PositionQ"][expr,pos]

returns True if pos is a valid position in expr that can be extracted with Extract.

ResourceFunction["PositionQ"][expr,{pos1,pos2,}]

returns True if all of the posi are valid positions.

ResourceFunction["PositionQ"][pos]

represents an operator form of ResourceFunction["PositionQ"].

Details

If expr is wrapped in Unevaluated, the test will be done on its unevaluated form. It will have no side-effect in this case.
The position specifications {} and {{}} are always valid, so ResourceFunction["PositionQ"] will always return True for these positions.

Examples

Basic Examples (4) 

Test if a position exists:

In[1]:=
ResourceFunction["PositionQ"][{a, b, c}, {3}]
Out[1]=

This does not exist because the list is too short:

In[2]:=
ResourceFunction["PositionQ"][{a, b, c}, {4}]
Out[2]=

This does not exist because the list is not deep enough:

In[3]:=
ResourceFunction["PositionQ"][{a, b, c}, {1, 2}]
Out[3]=

Test multiple positions at once:

In[4]:=
ResourceFunction["PositionQ"][{a, b, c}, {{1}, {2}}]
Out[4]=
In[5]:=
ResourceFunction["PositionQ"][{a, b, c}, {{1}, {4}}]
Out[5]=
In[6]:=
ResourceFunction["PositionQ"][{a, b, c}, {{1}, {1, 2}}]
Out[6]=

Scope (5) 

Test positions at different depths at the same time:

In[7]:=
ResourceFunction["PositionQ"][{a, b, {c}}, {{1}, {3, 1}}]
Out[7]=

Heads are allowed:

In[8]:=
ResourceFunction["PositionQ"][{a, b, {c}}, {{1}, {3, 0}}]
Out[8]=

Use an operator form to select elements that have a first part:

In[9]:=
Select[
 {a, {b}, c, {d, e}, {}},
 ResourceFunction["PositionQ"][{1}]
 ]
Out[9]=

Test positions in an Unevaluated expression:

In[10]:=
ResourceFunction["PositionQ"][Unevaluated[1 + 2], {1}]
Out[10]=

The evaluated form has no first part:

In[11]:=
ResourceFunction["PositionQ"][1 + 2, {1}]
Out[11]=

No side effects will be produced if Unevaluated is used:

In[12]:=
ResourceFunction["PositionQ"][Unevaluated[{Print[1]}], {1}]
Out[12]=

Publisher

Sjoerd Smit

Version History

  • 1.0.0 – 29 November 2021

Related Resources

License Information