How to get random.sample() from deque in Python 3?

python, python-2.7, python-3.x, random

Solution

The obvious way – convert to a list.

batch = random.sample(list(my_deque), batch_size))

But you can avoid creating an entire list.

idx_batch = set(sample(range(len(my_deque)), batch_size))
batch = [val for i, val in enumerate(my_deque) if i in idx_batch] 

P.S. (Edited)

Actually, `random.sample` should work fine with deques in Python >= 3.5. because the class has been updated to match the Sequence interface.

In [3]: deq = collections.deque(range(100))

In [4]: random.sample(deq, 10)
Out[4]: [12, 64, 84, 77, 99, 69, 1, 93, 82, 35]

Note! as Geoffrey Irving has correctly stated in the comment bellow, you'd better convert the queue into a list, because queues are implemented as linked lists, making each index-access O(n) in the size of the queue, therefore sampling m random values will take O(m*n) time.

Problem

I have a collections.deque() of tuples from which I want to draw random samples. In Python 2.7, I can use `batch = random.sample(my_deque, batch_size)`. But in Python 3.4 this raises `TypeError: Population must be a sequence or set. For dicts, use list(d).` What's the best workaround, or recommended way to sample efficiently from a deque in Python 3?

Original source

Related problems