Extracting a random sublist from a list in Python

user775093 picture user775093 · Nov 25, 2015 · Viewed 13.5k times · Source

I have a python dictionary as follows:

{'APPLE_PROVIDERS' : ["some", "provider","can","be", "null"],
  ....
}

What i want to do is get a random sublist from the list (which is a value) of a key. Not just one element, but a totally random sublist. Here is what I tried:

a_list = a_dict.get('APPLE_PROVIDERS', "")
for item in a_list[randrange(0,len(a_list)) : randrange(0,len(a_list))]:
  ...do something.. 

This thing has two problems :

  1. If the list is empty, or if the dict lookup fails, the program fails since randrange has (0,0) as arguments, which results in an error

  2. Many times both randrange() calls generate the same number, especially when the list is small. This returns an empty list. For example a_list[5:5]

So what is the best way to get a random sublist with above cases handled ? Also, I do not care about the ordering. Anything works. I just want a totally random sublist of either 0,1... till len(a_list) elements each time the for loop starts.

If the list can be changed in some other data structure which can hold similar elements, that works for me too.

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Nov 25, 2015

Sample it.

>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['some', 'can', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['can', 'null', 'provider']
>>> random.sample(["some", "provider", "can", "be", "null"], 3)
['null', 'some', 'provider']