The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Get A Random Set Of Items From From List

TL;DR

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

TODO: Pull subtitle into page object
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) )

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Get A Random Set Of Items From From List

-- tldr/

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

-- code
-- python

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']

-- /results

-- p

#+OLDNOTES:

-- p

import random

-- p

# 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.

-- p

# .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.

-- p

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)

-- p

return return_list

-- p

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

-- p

print(
get_up_to_n_random_items_from_list(input_list, 5)
)


-- categories
-- Python 

-- metadata
-- date: 2021-04-19 21:16:20
-- id: 01f3pdjz
-- status: published
-- type: scratch 
-- site: aws