I wanted to generate unique variable using iteration. I tried writing a code using globals() function but for some reason its not working.
for i in (range(0,7)):
for v in range(0,7):
globals()['element%s' % (i,v)] = []
I wanted to generate unique variable using iteration. I tried writing a code using globals() function but for some reason its not working.
for i in (range(0,7)):
for v in range(0,7):
globals()['element%s' % (i,v)] = []
The problem comes with the text formating.
Try globals()[f'elements{i,v}'] = []
instead.
You honestly just shouldn't play with globals
(reading material). But your error comes from the fact that the arguments you're trying to turn to a string (i, v)
have size 2, and there's a single place where you demanded a conversion: the %s
. If you want it to work there needs to be 2X %s
in your string:
for i in (range(0,4)):
for v in range(0,3):
print('%selement%s' % (i,v))
0element0
0element1
0element2
1element0
1element1
1element2
2element0
2element1
2element2
3element0
3element1
3element2