-1

Imaging I have these two lists:

 varnames=['a','b','c']
 values = [1,2,3]

I would like to asign the values of the second list to variables of the first list. I.e. the names of the variables are the strings of the first list.

Expected resuLt:

 a=1
 b=2
 c=3

Is that even possible? Is so With a one liner?

Thx.

EDIT 1: here there is a link How do I create variable variables? to an article about php. I.e it's not a duplication

JFerro
  • 3,203
  • 7
  • 35
  • 88
  • 2
    You can `exec` or `eval` code strings (and you can easily make code strings from what you have), but trust me you don't want to do that. Variables are supposed to mark your code for you to keep track of objects. If you start creating variables from arbitrary strings, you could start running into errors like accidentally reassigning an existing variable. Keep these arbitrary names in a dictionary or as attributes of an object via `setattr` (which is basically a dictionary). At the very least they'd be isolated from your code. – BatWannaBe Apr 10 '21 at 07:55
  • 2
    The duplicate is not about PHP (the author of the question just mentions it in passing to clarify what he means), but about Python, as all the answers clearly show - so, you should definitely read it. Anyway, short answer, as already suggested: don't do that, use a dict. – Thierry Lathuille Apr 10 '21 at 11:18

1 Answers1

2
#with one liner
dict(zip(varnames,values))
# output = {'a': 1, 'b': 2, 'c': 3}
Nk03
  • 14,699
  • 2
  • 8
  • 22
  • 2
    Not what OP asked for, but the correct solution. – deceze Apr 10 '21 at 07:41
  • Marking as duplicate has achieved yet another level. To a python question I get the tag duplicated to a question with a link about php! – JFerro Apr 10 '21 at 08:05
  • @JFerro The dupe is not about PHP. The asker just mentions it in passing. – deceze Apr 10 '21 at 08:18
  • This is the answer: for i,varname in varnames: exec(f'{varname} = {values[i]}') – JFerro Apr 10 '21 at 15:47
  • 1
    @JFerro `globals().update(zip(varnames, values))` — But that’s both horrible; you should not use nor need variable variables… – deceze Apr 10 '21 at 17:23