Get random slice/fraction of a list in python

Viewed 44

Imagine we have the following list:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now we want a random fraction of the previous list, i.e., a random sublist of length len(l) * frac. Therefore, if frac=0.2 the output list should have length 2 (0.2 x 10).

The following results are expected:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l_new = sample(list=l, frac=0.3) # [4, 6, 8]
l_new = sample(list=l, frac=0.6) # [0, 1, 4, 6, 7, 8]

How can I achieve this behaviour? I have looked at random.sample, however it works by supplying a number of elements rather than a fraction of elements.

1 Answers

An alternative is to use random.sample with k = int(len(l) * frac), like so:

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
frac = 0.3
l = random.sample(l, int(len(l) * frac))

print(l)
>>> [4, 7, 9]

Using it as a function:

# Randomly Sample a fraction of elements from a list
def random_sample(l, frac=0.5):
    return random.sample(l, int(len(l) * frac))
Related