Is there any way that I can automatically create new variables based on how many items I have in a Python list?
For instance, if I have a variable like this:
var = (json.loads(requests.get(list[0])).text)
Is it possible to automatically create additional variables like this, depending on the length of my list? I'd like to avoid manually writing out all my variables. Let's say my list has 4 items (length = 4).
var = (json.loads(requests.get(list[0])).text)
var1 = (json.loads(requests.get(list[1])).text)
var2 = (json.loads(requests.get(list[2])).text)
var3 = (json.loads(requests.get(list[3])).text)
I would appreciate any help. Thank you.
CodePudding user response:
Why don't you try to use a dict to handle this problem?
vars = {f'var{i}': json.loads(requests.get(yourlist[i])).text for i in range(len(yourlist))}
You can access your variables: vars['var1']
or vars.get('var1')
In general, creating new variables during the program execution isn't a good ideia.
CodePudding user response:
The direct answer to your question is to add the values in the global dictionary. It can be done with globals
, eval
, exec
. I don't recommend to do that because if you have a long list which change size then you have to remember how many elements you have.
Here an abstraction of the problem:
var_str_pattern = 'var{}'
val = ['smt', 'else']
for i, v in enumerate(val, start=1):
globals()[var_str_pattern.format(i)] = v
print(var1)
#smt
print(var2)
#else
You should use a dictionary approach as in the answer of Riqq.