sprksh sprksh - 3 months ago 7
Python Question

How can I select entries from list in random order in python

Question is simple. I have a list of say 10 entries, I am running a loop over it. What i want here is getting each entry exactly once but in random order.

What is the best and most pythonic way to do it?

Answer

You can use random.sample, it returns random elements preventing duplicates:

>>> import random
>>> data = range(10)
>>> print(random.sample(data, len(data)))
[2, 4, 8, 7, 0, 5, 6, 3, 1, 9]

The original list remains unchanged.

Comments