4
$\begingroup$

In the following example, how to easily get {2,4,10} using the [[{...}]] syntax?

aa = {2, 4, 6, {8, 10, 12}, 14, 16, 18, 20};
aa[[{1, 2}]]
(*{2,4}*)
aa[[{1, 2(* what to put here?? *)}]]
(*{2,4,10}*)
aa[[{1, 2(* what to put here?? *)}]]
(*{2,4,{10,12}}*)
$\endgroup$
5
  • 11
    $\begingroup$ As far as I know, that's not possible with Part. Use Extract instead: Extract[aa, {{1}, {2}, {4, 2}}]. $\endgroup$ Feb 12, 2020 at 22:13
  • 1
    $\begingroup$ if one is allowed to use Flatten, then Flatten[{aa[[{1, 2}]], aa[[{1, 2, 4}]][[3, 2]]}] gives {2, 4, 10} but I would also use Extract, much simpler. $\endgroup$
    – Nasser
    Feb 12, 2020 at 22:24
  • 1
    $\begingroup$ Join[aa[[{1, 2}]], {aa[[4, 2]]}] $\endgroup$
    – Bob Hanlon
    Feb 13, 2020 at 0:20
  • 2
    $\begingroup$ aa[[##]]&@@@ {1,2, {4, 2}} after Bob Hanlon here $\endgroup$
    – user1066
    Feb 13, 2020 at 0:20
  • $\begingroup$ As @HenrikSchumacher noted: Part is not the right tool for the job here; it cannot mix and match levels in this way. Extract is the correct function for this. $\endgroup$ Feb 13, 2020 at 12:34

1 Answer 1

1
$\begingroup$

Try this:

Part[Flatten[aa], #] & /@ {1, 2, 5}

(*  {2, 4, 10}  *)

If you need to first determine the positions of the desired elements do first

pos = Position[Flatten[aa], #] & /@ {2, 4, 10} // Flatten

(* {1, 2, 5}  *)

and then

Part[Flatten[aa], #] & /@ pos

(*  {2, 4, 10}   *)

Have fun!

$\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.