Basic Examples (9)
Look up part of an expression:
If the specified part is not found, a Missing object is returned:
Providing a third argument allows the default value to be provided:
When the part is present, the default is not evaluated:
Look up multiple parts:
Use Span syntax to look up a sequence of parts:
Count from the end of the list:
Use UpTo in a Span specification:
Use the operator form:
Scope (9)
Using zero as the part specification corresponds to the head of an expression:
Look up a nested part:
Get multiple nested parts:
Use a mix of part specifications:
Get the second column of a matrix:
Get part of an association by key:
Get part of an association by position:
Get a nested part of an association:
Or equivalently:
Use Unevaluated to look up part of the expression before it evaluates:
Only the returned part will evaluate:
Applications (1)
Create variants of First and Last that return a Missing object when the list is empty:
Properties and Relations (9)
LookupPart operates on the FullForm of expressions:
LookupPart returns the default value instead of failing if the first argument is atomic:
Compare to Part:
LookupPart[0] is equivalent to Head:
LookupPart[Sequence[]] is equivalent to Identity:
LookupPart has the SequenceHold attribute:
Part does not, so these are equivalent:
Using a Sequence as a part specification is similar to a Fold over the parts:
When the default value is not specified, LookupPart defaults to a Missing object that contains elements corresponding to what would be issued in a message when using Part:
Specifying part 0 always* succeeds without evaluating the third argument:
* Unless it doesn’t:
LookupPart has the NHoldAll attribute, so its operator form won’t be affected by N:
Possible Issues (2)
Unlike Lookup, the second argument of LookupPart behaves like the second argument of Part, so keys to associations must be wrapped in Key:
Attempting to use the key directly results in an error:
This is also true for Part:
However, if the keys are strings, Key is not necessary:
When using Span or All part specifications, LookupPart does not return partial results if any part of the sequence is missing:
This behavior is consistent with Part:
In this case, use of Map can yield partial results:
Neat Examples (1)
Create a new lookup function with a neat default value: