0

I'm trying to use a for-loop to create a lot of plots. Long story aside, I need to create a script that does something similar to this example:

text1="Hello"
text2="my"
text3="name"
text4="is"
text5="John"


for i in range(0,6):
    print(text{i})

Which would output the following:

 #Output:
    'Hello'
    'my'
    'name'
    'is'
    'John'

Is this possible in Python? Thanks!

  • 5
    You probably want to use a list instead of multiple variables. – Chris Jan 12 '22 at 15:32
  • @MichaelSzczesny That also depends on the variables being defined in the scope where you call `vars()`, which is not necessarily the case. – chepner Jan 12 '22 at 15:38
  • And *in general*, it's not. There are many corner cases which will work with one proposed hack, but not another. Providing such a hack without mentioning the exceptions does no one any good, and promotes the idea that doing something like this is anything other than a bad idea. – chepner Jan 12 '22 at 15:45

1 Answers1

2

You want a list, not a bunch of similarly named variables.

texts = ["Hello", "my", "name", "is", "John"]
for t in texts:
    print(t)
chepner
  • 497,756
  • 71
  • 530
  • 681