1

For example, If i had code similar to this:

x1 = 1
x2 = 2
x3 = 3

for i in range(3):
  #How do i get "x" + i and print the variable's value?
  print()
  • 4
    You put it into a data structure such as a list. The point of variable names is for your convenience while programming. If it's not convenient, don't use it. – Mateen Ulhaq Jul 01 '20 at 21:04
  • If you need to access variables dynamically, you should be using either a list or a dictionary. – Barmar Jul 01 '20 at 21:05

3 Answers3

3

If you want to iterate through the numbered variables without the use of an array,
you can use locals():

x1 = 1
x2 = 2
x3 = 3

for i in range(1,4): # Note that it's range(1,4) if you want 1, 2, 3
  print(locals()[f"x{i}"])

Output:

1
2
3
Red
  • 26,798
  • 7
  • 36
  • 58
1

not a huge amount of information about what you're asking here, but I think the below solves the it

x1 = 1
x2 = 2
x3 = 3
    
lst = [x1,x2,x3]

for i in lst:
  print(i)

output:

1
2
3
Blind Rabit
  • 105
  • 8
1

You can do it using eval function:

x1, x2, x3 = 1, 2, 3
for i in range(1,4):
  print(eval("x"+str(i)))

Output:

% python3 script.py
1
2
3
bousof
  • 1,241
  • 11
  • 13
  • Please consider the following: https://stackoverflow.com/a/1832957/13552470 – Red Jul 01 '20 at 21:23
  • 1
    Thanks for the link, very interesting! I made some performance tests and `locals()[f"x{i}"]` is actually ~15 times faster than `eval("x"+str(i))`. – bousof Jul 01 '20 at 21:37