# How to select random number of elements from a list?

Assume that I have a list

a = {1,2,3,4,5,6};


and I want to have a function that outputs a subset of the list such that with probability p=0.2 each element will be selected i.e. we toss a coin (that is not fair because p=0.2) when going trough the list and if it's heads we will take that element to the new list. At this moment I have implemented this as

z={};
Do[If[RandomChoice[{0.2, 1 - 0.2} -> {True, False}],
AppendTo[z, a[[i]]]], {i, 1, Length[a]}]


which seems a bit stupid way of doing it. Also I couldn't find a command in the documentation that does this.

• a = {1, 2, 3, 4, 5, 6}; rv = RandomVariate[BernoulliDistribution[.2], Length@a]; Pick[a, rv, 1]? – kglr Oct 4 '18 at 12:36
• Or Pick[ a, RandomChoice[{0.8, 0.2} -> {0, 1}, Length[a]], 1 ]. – Henrik Schumacher Oct 4 '18 at 12:38

SeedRandom
Pick[a, RandomVariate[BernoulliDistribution[.2], Length@a], 1]


{2, 3, 4}

Alternatively,

Flatten[RandomChoice[{.2, .8} -> {#, {}}] & /@ a]


{1, 5}

• Also: Reap[Scan[If[RandomChoice[{.2, 1 - .2} -> {True, False}], Sow[#]] &, {1, 2, 3, 4, 5, 6}]] – J. M.'s technical difficulties Oct 4 '18 at 12:45