[Python-ideas] shuffled as a way to shuffle an iterable
Xavier Combelle
xavier.combelle at gmail.com
Thu Sep 8 19:36:00 EDT 2016
When thinking about the shuffled thread, it occurred to me that it was
quite easy to pass an iterable and expect the iterable to be shuffled.
but two mentioned implementation are close to success but fail by not
taking this use case in account:
def shuffled1(iterable):
result = iterable[:]
random.shuffle(result)
return result
This one might fail because an iterable don't have subscript, but in the
case of range() it has. In this case it fail at the affectation place
def shuffled2(iterable):
random.sample(iterable,len(iterable))
This one perfectly work on range() but fail in a less specific iterable
without len like
shuffled2((i for i in range(5)))
and eventually this one work in all case of iterable
def shuffled3(iterable):
result = list(iterable)
random.shuffle(result)
return result
I don't think that the use case of shuffle an iterable is important
enough to create a function just to take care about it
but if one want to implement it in an analog way sorted is implemented
this should be take in account.
More information about the Python-ideas
mailing list