pick random item from set python code example
Example 1: python choose random element from list
import random
#1.A single element
random.choice(list)
#2.Multiple elements with replacement
random.choices(list, k = 4)
#3.Multiple elements without replacement
random.sample(list, 4)
Example 2: select a value randomly in a set python
import random
# with replacement = same item CAN be chosen more than once.
# without replacement = same item CANNOT be chosen more then once.
# Randomly select 2 elements from set without replacement and return a list
random.sample(set_name, 2)
Example 3: choose random index from list python
import random # Don't forget to install it first with pip install random
ahahfunny = ['ahah ', 'copy-', 'paste ', 'stack overflow',' go ', 'brrr']
# the biggest index in this list above is 5 (0 being 1 in programming)
print(ahahfunny[random.randint(0, 5)] # I like this way,
print(random.choice(ahahfunny)) # But this way is WAY thiccer...
Example 4: python randomly sample entry from a set
# Basic syntax:
import random
random.sample(your_set, number_of_elements)
# Where:
# - number_of_elements is the number of elements you want to sample
# without replacement from your_set
# Note, the samples elements are returned as a list. Use set(the_list)
# to convert back to a set
# Example usage:
your_set = {'a', 'bunch', 'of', 'unique', 'words'}
random.sample(your_set, 1)
--> ['words']
random.sample(your_set, 3)
--> ['words', 'of', 'a']