Automatically pass variables names to list

I have a long chain of code for a portion of a script. For example:

B1_2013 ='0_B1')
B2_2013 ='0_B2')
B3_2013 ='0_B3')
B4_2013 ='0_B4')
B5_2013 ='0_B5')
B6_2013 ='0_B6')
B7_2013 ='0_B7')
B8_2013 ='0_B8')
B9_2013 ='0_B9')
B10_2013 ='0_B10')
B11_2013 ='0_B11')
B1_2014 ='1_B1')
B2_2014 ='1_B2')
B3_2014 ='1_B3')
B4_2014 ='1_B4')
B5_2014 ='1_B5')
B6_2014 ='1_B6')
B7_2014 ='1_B7')
B8_2014 ='1_B8')
B9_2014 ='1_B9')
B10_2014 ='1_B10')
B11_2014 ='1_B11')

and so on ...

B11_2020 ='7_B11')

Ultimately, from these lines of code, I need to generate a list of variables (my_variables) that I can pass off to a function. For example:

my_variables = [B1_2013, B2_2013, B3_2013, B4_2013, B5_2013, B6_2013, B7_2013, B8_2013, B9_2013, B10_2013, B11_2013, \
                B1_2014, B2_2014, B3_2014, B4_2014, B5_2014, B6_2014, B7_2014, B8_2014, B9_2014, B10_2014, B11_2014]

Is there a more efficient approach to automatically generate hundreds of lines of code (e.g. B1_2013 ='0_B1') and so on...) following the first code example so that I can automatically generate a list of variables in the second code example (e.g. my_variables = [B1_2013, and so on...]?

>Solution :

Just make a list using a loop or list comprehension.

my_images = ['{i}_B{j}') for i in range(8) for j in range(12)]

Leave a Reply