How do I randomly select a variable from a list and then modify it in python?

Here is my python 3 code. I would like to randomly select one of the cell variables (c1-c9) and change its value to the same as the cpuletter variable.

import random

#Cell variables
c1 = "1"
c2 = "2"
c3 = "3"
c4 = "4"
c5 = "5"
c6 = "6"
c7 = "7"
c8 = "8"
c9 = "9"
cells = [c1, c2, c3, c4, c5, c6, c7, c8, c9]

cpuletter = "X"

random.choice(cells) = cpuletter

I get the message "Can not assign to function call" to "random.choice (cells)". I assume I’m just using it incorrectly? I know that you can use random selection to change a variable, as shown below:

import random
options = ["option1", "option2"]
choice = random.choice(options)
+4
source share
2 answers

Problem:

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

"3" = "X"

which is wrong.

list, :

cells[5] = "X"

:

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)

:

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

Random.choice(cells) cells, , # 0, # 0 - "1", "1" = "X" - , - , .

# cells[rand_elt_num]. :

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

, , , random.randrange().

-1

All Articles