-1

I am using Python 3.9 & have a list list1 = ['a', 'b', 'c', 'd'] I want to get a random item from the list without using any module like there is a module random in Python and a function random.choice(list1) I can use this but is there another way to get a random item from a list in Python without using any module?

Peter O.
  • 30,765
  • 14
  • 76
  • 91
Aditya
  • 835
  • 7
  • 18

4 Answers4

2

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))].
Peter O.
  • 30,765
  • 14
  • 76
  • 91
1

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])
Steve Nginyo
  • 183
  • 1
  • 11
1

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.

noob_coder
  • 66
  • 2
  • 5
-1

Something like this? Assuming your list contains only str

list1 = ['a', 'b', 'c', 'd']

def pick_random(array):
    return(list(set(list1))[0])

print(pick_random(list1))
Ryujinzz
  • 74
  • 3