Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a random list element of length n in Python

Tags:

python

random

I know you can use random.choice to choose a random element from a list, but I am trying to choose random elements of length 3. For example,

list1=[a,b,c,d,e,f,g,h]

I want the output to look something like:

[c,d,e]

Essentially I want to generate random sub-lists from the list.

like image 519
user2767074 Avatar asked Nov 27 '22 07:11

user2767074


1 Answers

Use random.sample() to pick a list of 3 elements:

random.sample(list1, 3)

Demo code:

>>> import random
>>> list1 = ['a', 'b', 'c' ,'d' ,'e' ,'f', 'g', 'h']
>>> random.sample(list1, 3)
['e', 'b', 'a']

If you needed a sublist, then you are stuck with picking a random start index between 0 and the length minus 3:

def random_sublist(lst, length):
    start = random.randint(len(lst) - length)
    return lst[start:start + length]

Which works like this:

>>> def random_sublist(lst, length):
...     start = random.randint(len(lst) - length)
...     return lst[start:start + length]
... 
>>> random_sublist(list1, 3)
['d', 'e', 'f']
like image 61
Martijn Pieters Avatar answered Jan 10 '23 04:01

Martijn Pieters