-2

I was curious: how does Python implement random.choice() from a set ?

I can imagine a very slow solution : choose a number n between 1 and len(set) and then iterate n times and return the item.

Thomas
  • 8,306
  • 8
  • 53
  • 92

2 Answers2

4

random.choice() does not actually support sets:

>>> import random
>>> s = {1, 2, 3, 4, 5}
>>> random.choice(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/random.py", line 256, in choice
    return seq[i]
TypeError: 'set' object does not support indexing

You can, however, convert the set to a list:

>>> random.choice(list(s))
2
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

Sets do not support object indexing. So you need to convert. Using a tuple instead of a list is more efficient for instantiation:

s = set([1, 2, 3, 4, 5, 6])
print random.choice(tuple(s))

If you are looking for clarity, an alternative choice is to use sample. However, it is not very efficient as internally as the first example it does convert anyway.

s = set([1, 2, 3, 4, 5, 6])
print random.sample(s, 1)

ref: Are tuples more efficient than lists in Python?

Community
  • 1
  • 1
Juan Leni
  • 6,982
  • 5
  • 55
  • 87