You can download this code by clicking the button below.
This code is now available for download.
This function allows for the random selection of an item from a list. It first uses the shuffle function from the random module to generate a random order iterator, then it uses the islice function from the itertools module to get the first item from the iterator.
Technology Stack : random, itertools, collections
Code Type : Function
Code Difficulty : Intermediate
def random_select(items):
import random
import itertools
from collections import deque
def shuffle(items):
result = deque(items)
while result:
index = random.randrange(len(result))
yield result.pop(index)
return itertools.islice(shuffle(items), 1)[0]
# JSON output