Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am pretty weak on the notion of pure functions, etc. I found a clean solution to my problem so in a sense I've already answered my own question but I don't feel I'm on terra firma.

I wanted to take a random sample from a list of lists with a different sample size for each list in the list of lists. I did the following which is clean and readable by the cognoscenti. I'll probably have trouble understanding this in a year. Comments and/or suggestions of better ways will be appreciated.

listoflists = {{1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10, 11, 12, 13}};

samplesizes = {2, 3, 1, 3};

out=Apply[RandomSample, Transpose[{listoflists, samplesizes}], {1}]
share|improve this question
The best solution is the one in the answer. I just wanted to note that you can write "Apply at level 1" as RandomSample @@@ Transpose[{listoflists, samplesizes}]. I find this more readable because I don't have to scan to the end of the expression to find the {1} part. It might not be easier to remember what it does in a year's time though. I do in fact use this frequently when the Transpose[{listoflists, samplesizes}] part is already constructed and stored somewhere. – Szabolcs Mar 20 '14 at 20:51
If it goes about clarity, also adding slots could help. RandomSample[#, #2] & @@@ is longer but maybe one will find it better. Or Table[RandomSample[listoflists[[i]], samplesizes[[i]]], {i, 4}] – Kuba Mar 20 '14 at 20:52
Duplicates: (3217), (10211), (15556), (26858), (32569), (71988) – Mr.Wizard May 24 '15 at 13:35


MapThread[RandomSample, {listoflists, samplesizes}]

is easier to understand

share|improve this answer
Especially with this – Kuba Mar 20 '14 at 21:07
Greeeaat!:) I haven't seen it before – Dr. belisarius Mar 20 '14 at 21:22
@Kuba The Select[] one is worth trying – Dr. belisarius Mar 20 '14 at 21:24
@belisarius This question clearly has been asked many times before. I posted several duplicate links above. Please choose one and vote to close. – Mr.Wizard May 24 '15 at 13:36

With global warming, characters are endangered. Save one... :-)

Inner[RandomSample, listoflists, samplesizes, List]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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