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
  • 59,172
  • 18
  • 144
  • 130
Monish K
  • 89
  • 1
  • 4

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
  • 506,650
  • 124
  • 909
  • 1,183