Python loop through a range of variables

I have a number of iE: x1to variablesx10

Now I would like to get the contents of each of them.

Is it possible to combine a variable like xi? Or should I just use lists?

The kind of syntax lost here, I believe! Something like what I'm thinking of:

while i <= 10:
    print(test+i)
+5
source share
3 answers

You should just use a list. Then you can iterate over the elements with a loop for.

You can also access the elements by index: x[i]. Keep in mind that list indices start from zero, not one. If the indexes are not small consecutive integers, you may need to use a dictionary instead of a list.

+9
variables = [x0, x1, x2, x3, x4, x5, x6, x7, x8, x9]
for x in variables:
    print x
+7

...

for i in range(10):
    print(eval("x" + str(i)))    
+3

All Articles