1

Let's assume I have 5 variables, A to E.

I've stuck them in a list, like so:

lst = [A, B, C, D, E]

Using the python random module, I did this:

random.choice(list) = "The Chosen Letter"

However, as I'm sure you know, I was so rudely slapped with a "can't assign to function call" error. That's not what I'm asking about, I know why that happens.

What I want to know is if it is, indeed, possible to assign a value to a random variable from a list or if I will have to code an ugly workaround.

For context, it's for a dynamic grid that I'm trying to code with randomly spawning text.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • just use a randomly generated index? – Paritosh Singh Dec 16 '18 at 15:39
  • 1
    The code you wrote is not valid python syntax. If your intention is to have variable named `The Chosen Letter` that holds a randomly-selected letter from a list, you have to invert the order : `the_chosen_letter = random.choice(list)`. Take a look at [rvalue vs lvalue](https://www.geeksforgeeks.org/lvalue-and-rvalue-in-c-language/) for an intuition on why the order matters. Notice that you cannot wrap `"the_chosen_letters"` around quotations, because then you're making it a string, and not a variable anymore (and strings should be rvalue, not lvalue). Particularly, your code'd be never valid – rafaelc Dec 16 '18 at 15:44

1 Answers1

0

You have not put "variables" into your list, you have created a list with five references to the same values in memory that A, B, C, ... point to.

In fact, it is impossible for a name to refer to another name. Names refer to values in memory, unidirectionally and exclusively.

Use a dictionary with string keys.

Setup:

>>> import random
>>> keys = ['A', 'B', 'C', 'D', 'E']
>>> my_vars = dict.fromkeys(keys)                                                                                     
>>> my_vars                                                                                                            
{'A': None, 'B': None, 'C': None, 'D': None, 'E': None}

Setting the value for a random key:

>>> my_vars[random.choice(keys)] = 'The chosen Letter'                                                                 
>>> my_vars                                                                                                            
{'A': None, 'B': 'The chosen Letter', 'C': None, 'D': None, 'E': None}

Accessing the "variables"

>>> my_vars['B']                                                                                                       
'The chosen Letter'
timgeb
  • 76,762
  • 20
  • 123
  • 145