Use Timestamp.to_period for actual year and month, create PeriodIndex by period_range and then convert values to format YYYYMmm by PeriodIndex.strftime:
from_year = 2018
last_year = pd.to_datetime('now').to_period('m')
print(last_year)
2021-07
months = pd.period_range(from_year, last_year, freq='M').strftime('%YM%m').tolist()
print (months)
['2018M01', '2018M02', '2018M03', '2018M04', '2018M05', '2018M06', '2018M07', '2018M08',
'2018M09', '2018M10', '2018M11', '2018M12', '2019M01', '2019M02', '2019M03', '2019M04',
'2019M05', '2019M06', '2019M07', '2019M08', '2019M09', '2019M10', '2019M11', '2019M12',
'2020M01', '2020M02', '2020M03', '2020M04', '2020M05', '2020M06', '2020M07', '2020M08',
'2020M09', '2020M10', '2020M11', '2020M12', '2021M01', '2021M02', '2021M03', '2021M04',
'2021M05', '2021M06', '2021M07']
If need all months add next year and then slice last value of months:
from_year = 2018
last_year = pd.to_datetime('now').year + 1
print(last_year)
2022
months = pd.period_range(from_year, last_year, freq='M')[:-1].strftime('%YM%m').tolist()
print (months)
['2018M01', '2018M02', '2018M03', '2018M04', '2018M05', '2018M06', '2018M07', '2018M08',
'2018M09', '2018M10', '2018M11', '2018M12', '2019M01', '2019M02', '2019M03', '2019M04',
'2019M05', '2019M06', '2019M07', '2019M08', '2019M09', '2019M10', '2019M11', '2019M12',
'2020M01', '2020M02', '2020M03', '2020M04', '2020M05', '2020M06', '2020M07', '2020M08',
'2020M09', '2020M10', '2020M11', '2020M12', '2021M01', '2021M02', '2021M03', '2021M04',
'2021M05', '2021M06', '2021M07', '2021M08', '2021M09', '2021M10', '2021M11', '2021M12']
Your solution with nested list comprehension with flatten:
from_year = 2018
last_year = datetime.datetime.now().year
print(last_year)
2021
year_list = list(range(from_year, last_year))
months = [f'{all_year}M{i:02}' for all_year in year_list for i in list(range(1,13))]
print (months)
['2018M01', '2018M02', '2018M03', '2018M04', '2018M05', '2018M06', '2018M07', '2018M08',
'2018M09', '2018M10', '2018M11', '2018M12', '2019M01', '2019M02', '2019M03', '2019M04',
'2019M05', '2019M06', '2019M07', '2019M08', '2019M09', '2019M10', '2019M11', '2019M12',
'2020M01', '2020M02', '2020M03', '2020M04', '2020M05', '2020M06', '2020M07', '2020M08',
'2020M09', '2020M10', '2020M11', '2020M12', '2021M01', '2021M02', '2021M03', '2021M04',
'2021M05', '2021M06', '2021M07', '2021M08', '2021M09', '2021M10', '2021M11', '2021M12']