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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With