Skip to content Skip to sidebar Skip to footer

How Do I Randomly Select A Variable From A List, And Then Modify It In Python?

Here's my python 3 code. I would like to randomly select one of the cell variables (c1 through c9) and change its value to the be the same as the cpuletter variable. import random

Solution 1:

Problem:

random.choice(cells) returns a random value from your list, for example "3", and you are trying to assign something to it, like:

"3" = "X"

which is wrong.

Instead of this, you can modify the list, for example:

cells[5] = "X"

Answer :

You can use random.randrange().

import random
cells = [str(i) for i in range(1,10)] # your list
cpuletter = 'X'

print(cells)
random_index = random.randrange(len(cells)) # returns an integer between [0,9]
cells[random_index] = cpuletter
print(cells)

Output:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
['1', '2', '3', '4', '5', '6', '7', 'X', '9']

Solution 2:

Random.choice(cells) returns a random element from cells, so if it returned element #0 and element #0 was the value "1", your original statement would essentially be saying "1" = "X" - obviously you can't assign the string literal to be something else, it's not a variable.

You'd instead want to get a random element #, and assign cells[rand_elt_num]. You could get the random element number by something simply like:

rand_elt_num = random.randint(0, len(cells)-1 )  #get index to a random element
cells[rand_elt_num] = "X"    # assign that random element

I think this is the same as what the other answer says, they just used random.randrange() instead.


Post a Comment for "How Do I Randomly Select A Variable From A List, And Then Modify It In Python?"