0

I have assigned the values to newly created variables in a loop and I want to print the values of the newly created variables.

for i,j in zip(range(0,2)):
    exec(f'cat{i} = 1')

I want to print cat_0 and cat_1 inside the loop

Paul H
  • 65,268
  • 20
  • 159
  • 136
Monish K
  • 109
  • 1
  • 5

1 Answers1

2

As commented by Juan, there’s never a good reason to do this. Use a regular list:

cat = [0] * 2
for i in range(0, 2):
    cat[i] = 1

… I’m assuming the actual code does something more interesting; otherwise you’d just do cat = [1] * 2 without a loop.

Or, if your i is a non-numeric (or a numeric but non-contiguous) value, use a dict:

cat = {}

for i in ['foo', 'bar', 'baz']:
    cat[i] = 1

Though, again, you can write this kind of code more concisely and without a loop:

cat = {key: 1 for key in ['foo', 'bar', 'baz']}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214