To mix the sequence evenly, random.shuffle() needs to know how long the input takes. The generator cannot provide this; you must materialize it to a list:
lst = list(yielding(x)) random.shuffle(lst) for i in lst: print i
Instead, you can use sorted() with random.random() as the key:
for i in sorted(yielding(x), key=lambda k: random.random()): print i
but since it also creates a list, thereโs little point in this way.
Demo:
>>> import random >>> x = [1,2,3,4,5,6,7,8,9] >>> sorted(iter(x), key=lambda k: random.random()) [9, 7, 3, 2, 5, 4, 6, 1, 8]
Martijn pieters
source share