6
$\begingroup$

What's the difference between Part and Position?

How can I "move" from the form used by Part to that of Position (and vicerversa?)

Thanks!

$\endgroup$
2
  • 2
    $\begingroup$ Have you read the documentation ? Part & Position $\endgroup$
    – Sektor
    Commented May 26, 2015 at 12:38
  • 3
    $\begingroup$ The results of Position are usually used in combination with Extract that precisely uses the format returned by Position. $\endgroup$ Commented May 26, 2015 at 15:24

1 Answer 1

8
$\begingroup$

The part specification used by Position is shared by Extract:

g = Plot[Sin[x], {x, 1, 5}];

pos = Position[g, _Directive]

Extract[g, pos]
{{1, 1, 3, 1}, {2, 11, 2}}

{Directive[ (* omitted *) ], Directive[GrayLevel[0.5, 0.4]]}

Note that Extract supports extracting multiple disjoint subexpressions at once. Part can only extract one of these at a time.* Each part specification such as {1, 1, 3, 1} needs to be converted from a list into a bare sequence. Available methods include pattern replacement and Function/SlotSequence along with Apply at level one (short form @@@):

Replace[pos, {x__} :> g[[x]], 1]

g[[##]] & @@@ pos

* These meaning the two elements in pos in my example. Part specifications at each level may be disjoint but apply to all parts in the extraction. Positions must have all but the last index in common.

m = Partition[Range@9, 3]

$\left( \begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{array} \right)$

m[[2, {1, 3}]]
{4, 6}

Index 2 applies to all elements extracted; one cannot extract (only) elements 4 and 9 with a single evaluation of Part for example, whereas you can with Extract:

Extract[m, {{2, 1}, {3, 3}}]
$\endgroup$
3
  • 1
    $\begingroup$ Argh, I hate it when commenting from the review queue (no answers shown) only to discover later on that your comment is fully superfluous. $\endgroup$ Commented May 26, 2015 at 15:26
  • $\begingroup$ @Sjoerd You'll notice that I have a conspicuously low ranking in the review queues relative to my other participation. I often resort to opening each question separately and acting from there as I don't like the limited information in the queue. $\endgroup$
    – Mr.Wizard
    Commented May 26, 2015 at 15:28
  • $\begingroup$ I like the queue as I spend 80-90% of my time here using an iPad. It's slightly more convenient that way (but only slightly; selecting SE stuff is a challenge on any iOS device). $\endgroup$ Commented May 26, 2015 at 15:42

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.