3
$\begingroup$

I have a list like this:

mylist = Range[5*#, 5 # + 4] & /@ Range[1, 5]

{{5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}, {25, 26, 27, 28, 29}}

Simple question: how can I extract the multiple elements of this list?

For example:

mylist[[1,3]] gives

7

mylist[[{1,3}]] gives

{{5, 6, 7, 8, 9}, {15, 16, 17, 18, 19}}

But how do I get for example the 3rd element of the first sublist and the 4th element of the fifth sublist? Something like {{7},{28}}?

I tried something like this:

mylist[[{{1, 3}, {5, 4}}]]

or

mylist[[{1, 3}, {5, 4}]]

But that didn't work...

Bonusquestion: why did that last code give the following result instead?

{{9, 8}, {19, 18}}

$\endgroup$
4
$\begingroup$

You are looking for Extract

Extract[mylist, {{1, 3}, {5, 4}}]

{7, 28}

What

mylist[[{1, 3}, {5, 4}]]

does is that it takes the first and third sublist, and then takes the fifth and fourth element from each of those lists.

$\endgroup$
2
  • $\begingroup$ Is there no shorthand for Extract? $\endgroup$ Jul 19 '17 at 17:30
  • 1
    $\begingroup$ @ImreVégh No, there isn't. You could say that Extract is a shorthand for what kglr posted, though. $\endgroup$
    – C. E.
    Jul 19 '17 at 17:30
3
$\begingroup$
mylist[[##]] & @@@ {{1, 3}, {5, 4}}

{7, 28}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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