How to get random item from a list in python3 without any module
Solution 1:
Random and pseudorandom generators will ultimately rely on some kind of module, if only to get a seed needed to produce pseudorandom numbers. One common example of a seed is time.time
found in the time
module, though it's not necessarily a good one. The only way without a module is to choose a fixed seed, but then only a fixed sequence of numbers is possible.
Besides the seed, there is the algorithm. One popular choice is the linear congruential generator (LCG). This algorithm is appropriate for learning purposes; however, LCGs are far from perfect and should not be used in security applications or serious simulations. See this answer: How to sync a PRNG between C#/Unity and Python?
There are two more things involved in the solution: generating a random integer, and choosing a random item from a list.
- Generating a random integer in [0, n); that is, building
RNDINTEXC(n)
. For that, see Melissa O'Neill's page. - Choosing a random item from a list, doing
list[RNDINTEXC(len(list))]
.
Solution 2:
If you don't want to use random
module, you can use time
module to generate pseudorandom integers.
import time
def get_random_number(upper_limit):
_timestamp = time.time()
_timestamp = int(_timestamp*1000000)
return _timestamp % upper_limit
def get_item_from_list(_list):
choice = get_random_number(len(_list))
assert choice < len(_list), "Index should be less than length of list"
return _list[choice]
print(get_item_from_list([10, 20, 13, 24, "ABS", "DEF"]))
You can use this to generate random items from a list.
Solution 3:
unless you want to create your own function
Method 1
import random
import math
variable = yourarray[math.floor(random.random()*len(yourarray))]
print(variable)
Method 2
import random
import math
def shuffle(array):
currentIndex = len(array);
temporaryValue= 0;
randomIndex = 0;
while (0 != currentIndex):
randomIndex = math.floor(random.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
return array
yourarray = shuffle(yourarray)
print(yourarray[0])