-1

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.

  • Don't do that. *Use a list* or a *dict* or another sort of container – juanpa.arrivillaga Jun 28 '22 at 19:23
  • So here, using a list comprehension, `vars = [requests.get(x).json() for x in list]`. Note, a `requests.Response` object has a `.json()` convenience method that is essentially equivalent to `json.loads(response.text)` – juanpa.arrivillaga Jun 28 '22 at 19:24

2 Answers2

0

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.

Riqq
  • 137
  • 1
  • 4
0

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

For the specific question:

n = 3
var_str_pattern = 'var'
for i in range(1, n+1):
    globals()[f'{var_str_pattern}{i}'] = json.loads(requests.get(list[i])).text

print(var1)
print(var2)
print(var3)

You should use a dictionary approach as in the answer of Riqq.

cards
  • 3,936
  • 1
  • 7
  • 25