-1

I want to declare variable name in sequence: Something like x_1, x_2, x_3,......., x_5 and assign value with them in python. Something like x_i = i^2.

n = 10
for i in range(1, n):
    x_i = i**2

print(x_2)

Can someone please help?

A. Chatterjee
  • 23
  • 1
  • 6
  • you could use `globals()` but i would not recommend it. just use a dict – luigigi May 05 '20 at 06:31
  • 1
    Does this answer your question? [How do you create different variable names while in a loop?](https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop) – Lith May 05 '20 at 06:33
  • 1
    It is not best practice to name variables sequences in a numbered way. Use a list instead. – Klaus D. May 05 '20 at 06:34
  • Use a list: `x=[]`, `for i in range(n):`, `x.append(i**2)`, `print(x[2])`. And learn about list comprehensions too, `x=[i**2 for i in range(n)]` – tevemadar May 05 '20 at 06:43

1 Answers1

0

You could use this but its not recommended:

n = 10
for i in range(1, n):
    globals()[f'x_{i}'] = i**2

print(x_2) #4
luigigi
  • 4,146
  • 1
  • 13
  • 30