1
years = list(range(2001,2003+1)
months = list(range(1,12+1)

I want to get the list as follows which consist all months and all years:

required = ['1.2001', '2.2001', '3.2001'...'12.2001', ....'1.2002', '2.2002', '3.2002'...'12.2002', '1.2003', '2.2003', '3.2003'...'12.2003']

My wrong code, but intended way of coding is below:

required = [x + '.' + (str(y) for y in years) for x in months]

Looking for simplest way of solving it.

2 Answers 2

3

You can generate the range of numbers and convert them to strings at the beginning itself

years  = list(map(str, range(2001,2004)))
months = list(map(str, range(1,13)))

Then you can use itertools.product like this

from itertools import product
print([".".join(item[::-1]) for item in product(years, months)])
# ['1.2001', '2.2001', '3.2001', '4.2001', '5.2001', '6.2001'...

Even simpler, your program can be fixed like this

print([y + '.' + x for x in years for y in months])

Note: I am assuming you are using Python 3.x

Sign up to request clarification or add additional context in comments.

2 Comments

but i want to solve using only for loops with out importing anything
@neha: It's strange that your attempt in the question uses a list comprehension, then. You can straightforwardly convert any list comprehension to a for loop if you want.
1
['%d.%d' % (m, y) for y in years for m in months]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.