shuffled as a way to shuffle an iterable
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.
On Fri, Sep 9, 2016 at 9:36 AM, Xavier Combelle <xavier.combelle@gmail.com> wrote:
and eventually this one work in all case of iterable
def shuffled3(iterable): result = list(iterable) random.shuffle(result) return result
This is the one obvious way to do this. Not all iterables can logically be shuffled, so the most normal approach would be to turn it into a list, then shuffle. Which is exactly what this does. ChrisA
participants (2)
-
Chris Angelico
-
Xavier Combelle