sprksh sprksh - 1 year ago 61
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download