Reputation: 53
I want to name an object "Nov2019" and I am trying the following:
Month = "Nov"
Year = "2019"
Year + Month = [100, 90, 80]
I want to have a list containing three integers which is named "Nov2019" by concatenation. Is it possible?
Upvotes: 0
Views: 695
Reputation: 27577
The simplest way is to wrap Year + Month
with locals()
:
Month = "Nov"
Year = "2019"
locals()[Year + Month] = [100, 90, 80]
print(Nov2019)
Output:
[100, 90, 80]
Note: Using locals()
, vars()
, globals()
, eval()
, exec()
, etc. are all bad practices.
Best to go with a dict
.
Upvotes: 1
Reputation: 487
You can use exec
method. A variable name can't start by a number, so a way to do that is invert the Month with Year. You can either put in a dictionary, but this approach is more aproximate to your question.
Month = "Nov"
Year = "2019"
exec(Month + Year + '= [100, 90, 80]')
print(Nov2019)
#[100,90,80]
Upvotes: 0
Reputation: 478
You can do this like so:
locals()[f"{Month}{Year}"] = [100, 90, 80]
or
globals()[f"{Month}{Year}"] = [100, 90, 80]
But a dictionary would be superior as the other answer mentions
Also, if you want your variable name/key to be "Nov2019", you should do Month + Year, not Year + Month.
Upvotes: 0
Reputation: 33335
It is possible if you put the variable inside a dictionary:
mydict = {}
Month = "Nov"
Year = "2019"
mydict[Year + Month] = [100, 90, 80]
Upvotes: 4