Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a random list element in python

Tags:

python

list

I'm trying to create a function that takes two lists and selects an element at random from each of them. Is there any way to do this using the random.seed function?

like image 587
Brandon Bosso Avatar asked Nov 29 '22 15:11

Brandon Bosso


2 Answers

You can use random.choice to pick a random element from a sequence (like a list).

If your two lists are list1 and list2, that would be:

a = random.choice(list1)
b = random.choice(list2)

Are you sure you want to use random.seed? This will initialize the random number generator in a consistent way each time, which can be very useful if you want subsequent runs to be identical but in general that is not desired. For example, the following function will always return 8, even though it looks like it should randomly choose a number between 0 and 10.

>>> def not_very_random():
...     random.seed(0)
...     return random.choice(range(10))
... 
>>> not_very_random()
8
>>> not_very_random()
8
>>> not_very_random()
8
>>> not_very_random()
8
like image 190
Andrew Clark Avatar answered Dec 12 '22 04:12

Andrew Clark


Note: @F.J's solution is much less complicated and better.


Use random.randint to pick a pseudo-random index from the list. Then use that index to select the element:

>>> import random as r
>>> r.seed(14)   # used random number generator of ... my head ... to get 14
>>> mylist = [1,2,3,4,5]
>>> mylist[r.randint(0, len(mylist) - 1)]

You can easily extend this to work on two lists.

Why do you want to use random.seed?


Example (using Python2.7):

>>> import collections as c
>>> c.Counter([mylist[r.randint(0, len(mylist) - 1)] for x in range(200)])
Counter({1: 44, 5: 43, 2: 40, 3: 39, 4: 34})

Is that random enough?

like image 26
MM S Avatar answered Dec 12 '22 06:12

MM S