-1
a = "Jack"
b = "Sam"

Now I want some way to create this:

c_{b value} = 10 

That means:

c_Jack = 10

And the following:

c_{a value} = 20 

That means:

c_Sam = 20
martineau
  • 119,623
  • 25
  • 170
  • 301
Me8saM
  • 3
  • 3
  • 5
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – matszwecja Jan 12 '22 at 13:13
  • 3
    Also, __DON'T__ – matszwecja Jan 12 '22 at 13:14
  • @matszwecja Why? – Guimoute Jan 12 '22 at 13:15
  • What are you trying to *accomplish* using this technique? Why isn't using a dictionary a better approach? – Scott Hunter Jan 12 '22 at 13:15
  • 1
    @Guimoute because it is a bad practice. Variable names shouldn't contain data. – juanpa.arrivillaga Jan 12 '22 at 13:15
  • 1
    See the linked dupe: use a dict. Variable variables *are* possible in python, but if you need to ask how to do them, you don't need them (there's a vanishingly small set of cases building debugging tools or stuff interacting with the interpreter in funny ways where I guess they might be needed). It's a fair (and common) q though, as some languages (e.g. TeX) pretty much require it. – 2e0byo Jan 12 '22 at 13:18
  • You can do this: `vars()[f"c_{a}"] = 10; print(c_Jack)` – flakes Jan 12 '22 at 13:26

1 Answers1

-2

This is actually a bad practice to do this. You better to use a dict.

BTW, you can do this:

In [3]: a = "Jack"

In [4]: exec(f'c_{a} = 10')

In [5]: c_Jack
Out[5]: 10


Mohammad Jafari
  • 1,742
  • 13
  • 17
  • 1. Don't answer questions that are clear duplicates. 2. This is a **terrible** idea, especially if there is *any* kind of user-inputted data involved, which there very often will be for this sort of thing. At the very least, you should be sanitizing your input values. Just.... don't. – MattDMo Jan 12 '22 at 13:27
  • Also, this will only work in the global scope – juanpa.arrivillaga Jan 12 '22 at 13:34
  • so many thanks.. thats work but why a bad practice?! i have a loop and i want to use varibales – Me8saM Jan 12 '22 at 13:47
  • @Me8saM Why is it bad practice? 1. You are losing control over your namespace - no IDE will be able to check whether the variable you are trying to use actually exists. 2. You can inject any sort of code during runtime which is __huge__ security risk 3. There are much cleaner, easier ways of achieving same functionalities for 99% of cases. Again, in case it was not stated enough: __If you had to ask how DO NOT DO THIS.__ If you want to have multiple related variables in a loop, contain them inside some kind of collection like list, set or a dictionary. – matszwecja Jan 12 '22 at 18:08