When you want to iterate sequentially over a list of numbers you will write:
for i in range(1000):
# do something with i
But what if you want to iterate over the list of numbers from the range (0..999) randomly? There is a need (in every iteration) to choose randomly the number that wasn’t chosen in any previous iteration and there is a need to iterate over all of the numbers from the range (0..999).
Do you know how to do that (smart)?
You can use
random.shuffle()to, well, shuffle a list:By the way, in many cases where you’d use a
forloop 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
ito access elements of a list, you should better shuffle the list directly:NOTE: You should bear the following warning in mind when using
random.shuffle()(taken from the docs: