Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random iteration in Python

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)?

like image 964
xralf Avatar asked Feb 12 '12 20:02

xralf


People also ask

How does random random () work in Python?

Python defines a set of functions that are used to generate or manipulate random numbers through the random module. Functions in the random module rely on a pseudo-random number generator function random(), which generates a random float number between 0.0 and 1.0.

How do you generate random in Python?

To generate random number in Python, randint() function is used. This function is defined in random module.


2 Answers

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.

like image 189
Niklas B. Avatar answered Sep 29 '22 03:09

Niklas B.


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 
like image 20
James Scriven Avatar answered Sep 29 '22 04:09

James Scriven