I am iterating over a Set in Python. In my application I prefer that the iteration be in a random order each time. However what I see is that I get the same order each time I run the program. This isn't fatal but is there a way to ensure randomized iteration over a Set?
Asked
Active
Viewed 1,979 times
2
-
I think you have to convert it to `list` . `s=set([1,2,3,4]); print random.choice(list(s))` – Kenji Noguchi Jul 23 '15 at 21:45
-
The easiest way to get those results is to turn it into a `list` and randomize that. I'd recommend doing it that way unless you're running into performance issues and can't afford creating the new `list`. – TigerhawkT3 Jul 23 '15 at 21:46
-
related (not duplicate): http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary – NightShadeQueen Jul 23 '15 at 21:53
2 Answers
4
Use random.shuffle
on a list of the set.
>>> import random
>>> s = set('abcdefghijklmnopqrstuvwxyz')
>>> for i in range(5): #5 tries
l = list(s)
random.shuffle(l)
print ''.join(l) #iteration
nguoqbiwjvelmxdyazptcfhsrk
fxmaupvhboclkyqrgdzinjestw
bojweuczdfnqykpxhmgvsairtl
wnckxfogjzpdlqtvishmeuabry
frhjwbipnmdtzsqcaguylkxove

Blair
- 6,623
- 1
- 36
- 42
1
You can use random.shuffle to shuffle your set:
>>> from random import shuffle
>>> a = set([1,2,3,4,5])
>>> b = list(a)
>>> shuffle(b)
>>> b
[4, 2, 1, 3, 5]
>>>

Ayush
- 41,754
- 51
- 164
- 239