Efficient way to loop through variables with number patterns in Python and append to a list?

Question:

so my variables are these:

answer1, answer2, answer3, answer4, …, answer20

and I want to append all of them to a list in order.
is there a neat way to do this?

I can just use extend and write all of them one by one but that’s inefficient

I’ve tried writing the variables manually but there is more that 20 variables that I’m working with

result_list = []
result_list.extend(answer1, answer2, answer3, answer4, ...)
Asked By: Its Ae

||

Answers:

Yeah, I guess you can just do this:

result_list = []
result_list.extend([globals()[f'answer{i}'] for i in range(1,21)])

This will get the values from the global scope, you can also use globals().get(f'answer{i}')

Answered By: D4Vinci
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.