Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Get A Random Set Of Items From From List

Use `random.sample()` to get random items from a list without repeating any

Code

import random

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

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

Results

['AR', 'AK', 'DE', 'CO', 'DC']

#+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) )