pigeonburger
pigeonburger

Reputation: 736

Python Random - change random value from list each time I use print

I know this is probably one of the easiest things in the world to do, and I'll feel like an idiot once someone answers, but please, help.

import random

stuff_list = ['a1', 'a2', 'a3']
stuff_item = random.choice(stuff_list)

print(stuff_item)
print(stuff_item)
print(stuff_item)

This makes it choose a random value (Ax) from stuff_list, but each time I print stuff_item I always get the same value from the list. How do I make it so that each time I use print, it randomises it again?

Upvotes: 0

Views: 159

Answers (2)

Rickey
Rickey

Reputation: 524

You can define a function that returns a new randomized item from the list each time the function is called:

from random import choice

def random_choice(stuff):
    return choice(stuff)


print(random_choice(['a1', 'a2', 'a3']))
print(random_choice(['a1', 'a2', 'a3']))
print(random_choice(['a1', 'a2', 'a3']))

Output:

a2
a3
a3

Upvotes: 1

Richard Ding
Richard Ding

Reputation: 382

The problem with your code currently is that random.choice(stuff_list) runs once and its value gets saved in stuff_item. Calling print(stuff_item) three times would simply print the value that is already stored

Try

import random

stuff_list = ['a1', 'a2', 'a3']
for _ in range(3): 
  print(random.choice(stuff_list))

Upvotes: 1

Related Questions