Home > Net >  Return a list from a for loop python
Return a list from a for loop python

Time:03-08

I want to combine inputs into a for loop in python and return the relevant dates. My code is as follows:

years =['2020', '2021'] 
months = ['JAN','FEB','MAR']

for YearItem in years:
    for item in months:
        vars1 = ('01 '   item   ' '   YearItem,)
    print(vars1)

My output currently returns ('01 MAR 2021') but I want it to return ('01 JAN 2020','01 FEB 2020',...,'01 MAR 2021')

CodePudding user response:

from itertools import product
vars = [f'01 {month} {year}' for year, month in product(years, months)]

See here itertools.product

CodePudding user response:

Bc with each months loop you overwrite the previous one. Try making a list so you have the desired format. Something like this?

years =['2020', '2021'] 
months = ['JAN','FEB','MAR']
final_list = []
for YearItem in years:
    for item in months:
        final_list.append('01 '   item   ' '   YearItem)
print(final_list)

Output:

['01 JAN 2020', '01 FEB 2020', '01 MAR 2020', '01 JAN 2021', '01 FEB 2021', '01 MAR 2021']

CodePudding user response:

I'm guessing you want a list return of vars1?

years =['2020', '2021'] 
months = ['JAN','FEB','MAR']

list1 = []
for YearItem in years:
    for item in months:
        vars1 = ('01 '   item   ' '   YearItem,)
        list1.append(vars1)
  • Related