3

Say I have a thousand variables. v1,v2,v3,...,v1000, but they are just variables not in a list.

Is there any way I can loop them.

I know in c I can use Marcos.

But how can I do it in python? Any hints will be helpful.

5
  • An example of the data and the expected output would be nice. Commented Feb 5, 2015 at 23:37
  • 2
    thousands of variables??? wouldn't it be easier to use arrays? i mean arrays were made to solve this problem.. Commented Feb 5, 2015 at 23:37
  • You could, but there is no way it would be better than using a list. Commented Feb 5, 2015 at 23:38
  • @bakriawad The problem is they are not in arrays or in files. They are just variables in another source code. Commented Feb 5, 2015 at 23:39
  • @AlexWei that was helpful, should include in question along with what the variables are or what they look like.. i don't know python but i am thinking you are looking for a way the compiler would look for all the variables there and gets them into a list then execute a loop. try looking for a method that returns all the variables in a code. Commented Feb 5, 2015 at 23:42

2 Answers 2

2

Alternative way is to use vars(). for example:

v1='dd';
v2=32;
v4=12;


import re
re_p = re.compile('^v\d+')

var_list = vars().copy()

for a_var in (v for v in var_list if re_p.match(v)):
    print(a_var, var_list[a_var])

Prints:

v1 dd
v4 12
v2 32
Sign up to request clarification or add additional context in comments.

Comments

2
v1 = 'foo'
v2 = 'bar'
v3 = '42'

for i in range(1,4):
  print vars()['v' + str(i)]

1 Comment

@taesu Thanks for your answer. I have checked your code have answered my question. Since Marcin give the link of the vars and more formal than your answer. I will accept his as the answer and upvote your answer. Hope you don't mind. Thanks your answer again. It helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.