0

I've read https://bugs.python.org/issue33098, which is about the following behavior of Python 3

a = {'1': 42, '2': 84}  # keys are str on purpose, c.f. the issue

import random
random.choice(a.keys())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/nix/store/.../lib/python3.7/random.py", line 262, in choice
    return seq[i]
TypeError: 'dict_keys' object does not support indexing

I've discovered that this functionally equivalent call succeeds just fine

random.sample(a.keys(), 1)[0]
'1'

Given the justification on the issue, is there any deeper principled reason why the two functions should behave differently, are there practical considerations for making sample() more flexible in its arguments, or is it all just an implementation accident?

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.