random iteration in Python
Here's a different approach to iterating a list in random order. This doesn't modify the original list unlike the solutions that use shuffle()
lst=['a','b','c','d','e','f']
for value in sorted(lst,key=lambda _: random.random()):
print value
or:
for value in random.sample(lst,len(lst)):
print value
You can use random.shuffle()
to, well, shuffle a list:
import random
r = list(range(1000))
random.shuffle(r)
for i in r:
# do something with i
By the way, in many cases where you'd use a for
loop over a range of integers in other programming languages, you can directly describe the "thing" you want to iterate in Python.
For example, if you want to use the values of i
to access elements of a list, you should better shuffle the list directly:
lst = [1970, 1991, 2012]
random.shuffle(lst)
for x in lst:
print x
NOTE: You should bear the following warning in mind when using random.shuffle()
(taken from the docs:
Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated.
People often miss opportunities for modularization. You can define a function to encapsulate the idea of "iterate randomly":
def randomly(seq):
shuffled = list(seq)
random.shuffle(shuffled)
return iter(shuffled)
then:
for i in randomly(range(1000)):
#.. we're good to go ..