Wednesday, August 15, 2012

Choose random elements from a list.

Hi! there exists a simple library function that can be found in the random module to sample out a list of length N which contains the random elements from a given list. The original list remains unchanged.

Here is the simple code snippet.

import random

old_list = [1,2,3,4,5]
new_list = random.sample(old_list, 3)

Running the above code will give us a list of length 3 containing random elements from old_list.
O/P:
>>> random.sample(a, 3)
[5, 1, 2]
>>> random.sample(a, 3)
[1, 5, 2]
>>> random.sample(a, 3)
[1, 2, 5]
>>> random.sample(a, 3)
[2, 1, 5]
>>> random.sample(a, 3)
[5, 1, 3]
>>> random.sample(a, 3)
[1, 3, 2]


*Note: If the old_list contains repeated elements then its not guaranteed to have unique element in the new_list.

Reference: http://docs.python.org/library/random.html

No comments:

Post a Comment