Home

Get A Random Set Of Items From From List

Use [TODO: Code shorthand span ] to get random items from a list without repeating any

python
import random

items = [
    'AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 
    'CO', 'CT', 'DE', 'DC']

print(random.sample(items, k=5))
results start

#+OLDNOTES:

import random

# Note that .choices can return the same thing multiple times. # This means it can duplicate. It also means, you can ask for # more items than are in the list.

# .sample() is "without replacement" so each item can be chosen # only one time. If the list is smaller than the requested number # of items (via `k`) then the script goes boom.

def get_up_to_n_random_items_from_list(source_list, requested_number_of_items_to_get): items_to_get = min(requested_number_of_items_to_get, len(source_list)) return_list = random.sample(source_list, k=items_to_get)

return return_list

input_list = ['AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC']

print( get_up_to_n_random_items_from_list(input_list, 5) )

~ fin ~