-2

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)] = []
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
Vivek
  • 3
  • 4
  • 2
    You can use a [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) directly – BlackBear Jun 22 '20 at 19:43
  • "for some reason its not working" -> Could you be more specific? Do you get an error message or some other indicator of what went wrong? – Niklas Mertsch Jun 22 '20 at 19:45
  • Yes. This is the error. 'TypeError Traceback (most recent call last) in 1 for i in (range(0,7)): 2 for v in range(0,7): ----> 3 globals()['element%s' % (i,v)] = [] 4 TypeError: not all arguments converted during string formatting' – Vivek Jun 22 '20 at 19:48

3 Answers3

0

The problem comes with the text formating.

Try globals()[f'elements{i,v}'] = [] instead.

  • It does create the variables but when I call that variable its shows this error: 'name 'elements' is not defined'. I'm looking for output something like element00, element01, element02 and so on. – Vivek Jun 22 '20 at 20:06
0

You can use something like this. Note that modifying globals() is rarely a good idea, have a look at this instead.

for i in range(5):
  globals()['myvar'+str(i)] = i**2

print(myvar2)
print(myvar3)

Output:

4
9
PApostol
  • 2,152
  • 2
  • 11
  • 21
0

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
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143