1

I have a set of "question" objects that I want to put in a list. There are several hundred of these objects, and each is named in a numbered fashion: question1, question2, etc.

I can build the list by typing them all in:

question_list = [question1, question2, question3, ...
                ... question500]

but it seems there must be a simple and easy way to build the list, something like:

for i in range(500):
    question_list.append(questioni)

Any suggestions?

4
  • Although eval() function doesn't fit best practices you could use it. for i in range(500): question_list.append(eval(f"question{i}")) Commented Apr 16, 2020 at 15:53
  • 6
    Sounds like the original design should be changed to a list instead of having 500 variables Commented Apr 16, 2020 at 15:55
  • 4
    Anytime you find yourself with lots of variables with names like question1, question2, it's time for a refactor. You will never find a sustainable way forward with that code. It should be question = [] and then question[0], question[1] Everything will fall into place after that. Commented Apr 16, 2020 at 15:57
  • Or a dictionary {'q1':question1,'q2':question2...} Commented Apr 16, 2020 at 16:00

2 Answers 2

1

You can access your variables from globals() method.

for i in range(500):
   question_list.append(globals()['question{}'.format(i)])
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, probably that would be a better solution. globals() returns a dictionary with the current global symbol table, so you can access all the variables form there.
1

I have tried this:

variable1 = "first question"
variable2 = "second question try"

all_values = dir()

output = []
for v in all_values:
  if('variab' in v):
    output.append(eval(v))

print(output)

The dir() function shows all string names of the variables, if you only want the output of the variables questionI, you could use the eval() method to get the object inside the questionI (I've supossed that it's a string value). I think that if you change the if statement and use the string 'question' it could work.

Comments

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.