Search code examples
pythonrandom-seed

Usage of seed() in Python random module


I am new to coding and learning Python. I am stuck at a position described below. If I sound naive or foolish by asking this question, please forgive me as I am through my initial days of coding.

import random
a = ['8', '13', '29', '36']
random.seed(0)
b = random.choice(a)
print(b)

So far I have understood that we use seed() to get a specific value from a random iteration. My question is - "Is there any way to identify which seed integer is required to fetch a specific item from the list?" I mean, if I put 0 as seed, the output will be 36(I have checked) but if we put seed as 179, the output is coming as 13. Is it completely random that any integer if we put as seed will 'choice' any arbitrary item of the given list and continue to give the output through out the iterations or it follows some specific algo which I am not understanding?


Solution

  • "Random" generators in computers don't actually generate random numbers; they generate pseudo-random numbers: The algorithms they use are actually deterministic, but they aim to make it difficult to predict which number will come up next by performing complex operations on them. To do that, they need to start with some value to begin with, and that value is the seed. Normally, they take a seed value from the current time which they obtain from your system (which is good enough since it will be near impossible to predict at which exact moment the script will run), but you can use seed() to provide a seed value chosen by you. Once they have that, they will generate the first random number by using that seed value as input to the algorithm, and then they will continue basing each random number on the previous one.

    So, to sum it up: No, seed() is not meant to allow you to pick a predetermined item from your list, it's meant to provide the random generator some input data to begin with.

    This is, by the way, the reason why the built-in random module is entirely unsuitable for critical purposes where "genuine" random numbers are needed, such as encryption; it's deterministic, so determined attackers can use that weakness to their advantage.