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, ...)
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}')
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, ...)
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}')