13
$\begingroup$

From the statement in the documentation:

Extract[expr,{i,j,…}] is equivalent to Part[expr,i,j,…].

So basically Extract is just a listable version of Part. So I look at the following example:

expr = f[g[1, 2], {h[3],i[4]}];

Let's take some parts out as follows:

{Part[expr,1,2],Part[expr, 2, All, 1]}

{2, {3, 4}}

Now I try to combine the multiple Parts using a single Extract:

{Extract[expr,{1,2}], Extract[expr,{2,All,1}]}
Extract[expr, {{1, 2}, {2, All, 1}}]

and it fails. But why? Isn't it the purpose of Extract to be able to combine multiple Parts commands into a single Extract?


Issue recently discussed on Live CEOing Ep 488: Language Design in Wolfram Language [SubValues, List, Extract and More] and a potential solution may be coming in a future version.

$\endgroup$
3
  • 8
    $\begingroup$ All is not a position per se. Neither is a Span[]. The purpose of Extract is to extract parts found by Position. (The previous sentence is my opinon, not necessarily a fact.) -- There's also Extract[expr, {p1, p2,...}, Hold], which Part does not do. $\endgroup$
    – Michael E2
    Commented Jan 26, 2020 at 22:37
  • 8
    $\begingroup$ Another difference, Extract has an operator form, Part does not. $\endgroup$ Commented Jan 26, 2020 at 23:09
  • 3
    $\begingroup$ To quote the docs: "The position specifications used by Extract have the same form as those returned by Position" $\endgroup$
    – Michael E2
    Commented Sep 13, 2021 at 4:00

1 Answer 1

6
$\begingroup$

Extract works with standard positions specifications, the same ones returned by Position, and used by functions like Delete or ReplacePart. These functions are all cross-compatible: the output of one works with the others. Extract is simple, predictable, and thus very suitable for working with programmatically generated position specifications. The number of extracted elements will be the same as the number of position specifications you pass in.

However, writing positions specifications manually is cumbersome. There is no concise way to extract multiple parts at a certain depth, e.g. data[[2, 3, {4,5}]]. All and ;; cannot be used (as they are also meant for specific levels). These is why we have Part.

In summary,

  • I use Extract when dealing with positions specifications generated by other functions, usually Position. Extract takes a list of position specifications, each one of which must be complete and stand on its own.
  • I use Part when specifying what to extract manually. We can write what to extract separately at each level/depth of the expression. Thus a single part specification can refer to multiple parts of the expression at the same time.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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