-1

How can I print multiple variables that are named for example var0, var1, var2, var3, etc, using a for loop

#these are my variables
var0 = 'empty'
var1 = 'something'
var2 = 'something again'
var3 = 'last thing'

for x in range(0,4):
    print(varX)

I want the varX expression to be able to print each variable at a time.

  • 1
    I think you should consider `dictionary` object. [(intro)](https://www.tutorialspoint.com/python/python_dictionary.htm) – Alexandre B. Jun 28 '19 at 13:21
  • Possible duplicate of [To convert string to variable name](https://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name) – David Zemens Jun 28 '19 at 13:28
  • The problem is, I must use variable strings. –  Jun 28 '19 at 13:28
  • there is *no good reason* to use numbered variables here. use a proper container like a list or a dict. – David Zemens Jun 28 '19 at 13:29
  • Why *must* you use strings? Is this a homework assignment? It would be nice if you explain the reason here, because using strings > variable names is really not a pythonic way of doing things. – David Zemens Jun 28 '19 at 13:30

4 Answers4

1

Don't use numbered variable names in the first place; use a list.

vars = ['empty', 'something', 'something again', 'last thing']

for var in vars:
    print(var)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • I wish it would've been easier. I am working with a NLP library and I must use separated variables. –  Jun 28 '19 at 13:27
  • 1
    @YassineLachgar I think you must be misunderstanding something. If the library requires strings, then the library is **not** taking variables, it's simply taking strings. I'd be absolutely shocked to see that some library is invoking an `eval` against the arguments you pass to it. If you can revise your question with [MCVE] that illustrates the *actual problem* you're facing there might be a better solution. – David Zemens Jun 28 '19 at 13:35
1

you can try:

#these are my variables
var0 = 'empty'
var1 = 'something'
var2 = 'something again'
var3 = 'last thing'

for x in range(0,4):
    print(eval("var" + str(x)))

more examples on eval() here. What eval() does is execute python code within itself (source)

Lucas Wieloch
  • 818
  • 7
  • 19
0

as already said it's better to use array or dictionary. However you can achieve this via globals() function

for x in range(0, 4):
    print(globals()['var' + x])
Mikhail Tokarev
  • 2,843
  • 1
  • 14
  • 35
0

You can create a dictionary as follows:

d = dict()
d['var0'] = 'empty'
d['var1'] = 'something'
d['var2'] = 'something again'
d['var3'] = 'last thing'
for x in range(0,4):
    print(d["var"+str(x)])
mik1904
  • 1,335
  • 9
  • 18