# How does random work?

uhh, @mtf or anyone:
how can i do to make a random selctor code block to select only one item from the given list, only 1 time each. so far i have come:

``````import random
vex = ['Sunny', 'Cloudy', 'Rainy' ,'Stromy']
me1 = vex[random.randint(0, 3)]
me2 = vex[random.randint(0, 3)]
me3 = vex[random.randint(0, 3)]
me4 = vex[random.randint(0, 3)]
print ("today is " + me1)
print ("tommorow will be " + me2)
print ("2 days from now will be " + me3)
print ("3 days from now will be " + me4)

``````

This gave me output of random weather; but sometime when re-running the code it gave two more or printed statement with a same weather which i dont want . Simply make this code to give a different weather on each printed statement and the weather must not be reapeted in two or more printed statement (kind of hard to get my question right?, elseway if not understood read 2-3 times )

1 Like

Perhaps `.sample` or `.shuffle` might be close to what youâ€™re after-
https://docs.python.org/3/library/random.html

The important bit would be selection without replacement.

2 Likes

uhhhh, i dont have a very good skills of reading long text and skills of efficient documentation. so i couldnt undersatnd it clearly.

still want to wait for the answer from the side of @mtf.

1 Like

Letâ€™s rule out time-complexity for a moment, but the `random.sample(n, k)` method allows you â€śchooseâ€ť k elements out of a list of n (you define the list yourself). So once you chose an element, you can also remove the element you chose from the list n and call `random.sample(n, k)` again. Note, your list would be `n` here and the amount of items taken at a time `k` is `1`.

2 Likes

uhhh, i known that devlopers these days looks for a shorthand way. But the concept is still not clear i asked in the question to edit the question yourself and write the desired output so i can correspond and understand like @mtf always does in his every answers

still want to wait for the answer from the side of @mtf.

1 Like

The probability of duplication here is very good. If weâ€™re looking for an algorithm approach, as opposed to using random methods mentioned above, then we need a way to create a new random list from the `vex` list.

``````>>> from random import randrange
>>> vex = ['Sunny', 'Cloudy', 'Rainy' ,'Stormy']
>>> new_vex = []
>>> while (len(vex)):
new_vex.append(vex.pop(randrange(len(vex))))

>>> new_vex
['Cloudy', 'Stormy', 'Sunny', 'Rainy']
``````

In most languages, including Python, there is more than one way to skin a cat. Note our use of `list.pop()` above. That is a method you may wish to read up on.

Bottom line, we have no way to simulate randomness that is as simple and straight forward as the methods in the `random` module. Suggest use this opportunity to explore that module in all its flavors.

3 Likes