2

I've got 20 variables which are named line1, line2, line3, ..., up to line20.

Is there a way in Python to use a for loop to reference each of these variables in sequence, i.e., iterate through them? Something to this effect:

for i in range(1, 21):
    print(line + str(i))

Although I know that's wrong.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

4 Answers4

4

Don't use separate variables like that. Use a list. Having a bunch of similarly-named variables is an anti-pattern.

lines = []

# add 20 strings to the list

for line in lines:
    print(line)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

Move your variables in to a list.

So if line1 = "foo" and line2 = "boo" just do this instead:

a = ["foo", "boo"]

for i, v in enumerate(a):
    print("{}: {}".format(i + 1, v))

Will give you an output like:

1: foo
2: boo 

Or if you simply want to just iterate over that array then just do:

for i in a:
    print(i)

Which will simply output:

foo
boo
idjaw
  • 25,487
  • 7
  • 64
  • 83
1

I agree with others that it is better to move to a list, but you could use eval:

>>> line1 = "This"
>>> line2 = "isn't"
>>> line3 = "Recommended"
>>> for i in range(1,4):
    print(eval("line" + str(i)))


This
isn't
Recommended

In addition to the point that it is more natural to use a list, this also isn't recommended because eval can be dangerous. While eval does have some uses and can be used safely (though never safely on a user-input string), avoiding refactoring your code isn't a valid use case. So -- in addition to making your code easier to read and easier to maintain, using lists or dictionaries can also make your code more secure since then you are less likely to use eval in a hackish manner.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
0

lst = ['line0', 'line1', 'line2']

for line_num, line_name in enumerate(lst):
    print 'Line str: %s, Line number: %s' % (line_num, line_name)

this will print: Line str: line0, Line number: 0 Line str: line1, Line number: 1 Line str: line02, Line number: 2

Lior Pozin
  • 393
  • 1
  • 5
  • 14