0

New to Python here. I want to create new variables with names taken from strings in a list. (I looked around and there were a couple questions with similar names, but it looked like they were trying to do different things.)

Here is a simplified example to show what I'm trying to do:

mylist = ["a", "b", "c", "d"]

for item in mylist:
    item = input("What do you want " + str(item) + " to be defined as?")

If I run through it and enter what I want each of the variables I am trying to create to be...

What do you want a to be defined as?"apple"
What do you want b to be defined as?"bob"
What do you want c to be defined as?"cat"
What do you want d to be defined as?"dog"

I am TRYING to do the equivalent of defining

a = "apple"
b = "bob"
c = "cat"
d = "dog"

But, when I check to see if it worked, I get:

NameError: name 'a' is not defined

Please help!

(Or, if I could rename an already-defined variable X with a name pulled from a list, I could make that work to do what I want also. It's just the creating a variable name from a string within a list part that is eluding me.)

Also, note: I am NOT trying to change the entries in mylist (i.e. to change it to mylist = ["apple", "bob", "cat", "dog"]). I'm just trying to pull names from mylist to use as variables to do other things elsewhere. I want mylist to stay just ["a", "b", "c", "d"].

Thanks

Nate L
  • 1
  • 1

2 Answers2

1

You can do it with a dictionary:

mylist = ["a", "b", "c", "d"]

mydict = {}

for item in mylist:
    mydict[item] = input("What do you want " + str(item) + " to be defined as?")

More about dictionaries you can read here: https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries

Daria Pydorenko
  • 1,754
  • 2
  • 18
  • 45
0

I suggest to use a dict instead of a list, so that the dict will represent a mapping between variable names and their associated value:

variables = ['a', 'b', 'c']
mapping = {v: None for v in variables}

for variable in variables:
    mapping[variable] = input(...)

Anyway, if you really need to dynamically create new variable, you can still rely on exec:

var = 'a'
value = 'apple'
# Similar to a = 'apple'
exec('{} = "{}"'.format(var, value))

After having executed those lines, you can check that a is defined and has the correct value:

assert a == 'apple'

Btw, relying on exec is not a good idea in general (especially if you have no control on what is provided to input!).

Guybrush
  • 2,680
  • 1
  • 10
  • 17