How To Print The Values Assigned In Loop In Python?
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')
Solution 1:
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']}
Post a Comment for "How To Print The Values Assigned In Loop In Python?"