1

I was trying to create dynamically variables in python by the following code:

for i in range (1,10):
    xi = 'wow'

Surprisingly this didn't show any error, which I did expect. But on calling the variable, I experienced something unexpected:

>>>x1
NameError: name 'x1' is not defined

What supressed the error in the creation and what raised the error here?

Joshua
  • 4,917
  • 1
  • 10
  • 33

2 Answers2

2

See Yosua's answer.

Please check out this question too: How do you create different variable names while in a loop?

If you really need to do it without a dictionary, you can use Collin's answer:

for i in range (1,10):
    exec(f"x{i} = 'wow'")

However, I would not recommend using this. It is not a very elegant solution.

PythonSherpa
  • 2,390
  • 2
  • 16
  • 39
0

What do you mean by Dynamic Python Variable?

for i in range (1,10):
    xi = 'wow'

This code basically assigning one variable xi to a string 'wow' 9 times.

And you haven't defined x1 anywhere (Python will not change xi into x1 or x2 they are all different variable name)

Yosua
  • 411
  • 3
  • 7