Select an item from a set in Python
What about converting to list and sorting?
my_list = list(my_set)
my_list.sort()
chosen_element = my_list[0]
you could use a function with memoization
def get_random(my_set,memo={}):
if id(my_set) not in memo:
memo[id(my_set)] = random.choice(list(my_set))
return memo[id(my_set)]
a_set = set([1,2,3,4,5])
print get_random(a_set)
print get_random(a_set)
this would always give you the same value as long as you passed in a_set
... (a different set would give a different answer)
if you wanted to make sure the item was still in the set you could change the memo if check
def get_random(my_set,memo={}):
if id(my_set) not in memo or memo[id(my_set)] not in my_set:
memo[id(my_set)] = random.choice(list(my_set))
return memo[id(my_set)]