Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create tuple from ranges in python

Is there a way in python to create a tuple of months and years (as: [(2020, 1),(2020,2)...] ) by using the tuple() function?

My code:

monthyears = []
for y in range(2020,2017,-1):
    if y == 2018:
        m_end = 6
    else:
        m_end = 0
    for m in range(12,m_end,-1):
        monthyears.append((y,m))

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[(2020, 12),
 (2020, 11),
 (2020, 10),
 (2020, 9),
 (2020, 8),
 (2020, 7),
 (2020, 6),
 (2020, 5),
 (2020, 4),
 (2020, 3),
 (2020, 2),
 (2020, 1),
 (2019, 12),
 (2019, 11),
 (2019, 10),
 (2019, 9),
 (2019, 8),
 (2019, 7),
 (2019, 6),
 (2019, 5),
 (2019, 4),
 (2019, 3),
 (2019, 2),
 (2019, 1),
 (2018, 12),
 (2018, 11),
 (2018, 10),
 (2018, 9),
 (2018, 8),
 (2018, 7)]

for loops are fine, but I’d like to learn a new trick, if it exists.

>Solution :

Try this:

>>> tuple((y, m) for y in range(2020, 2017, -1) for m in range(12, (6 if y == 2018 else 0), -1))

# you can use 'in' if you want to check multi-year
# >>> tuple((y, m) for y in range(2020, 2017, -1) for m in range(12, (6 if y == 2018 else 0), -1))

((2020, 12),
 (2020, 11),
 (2020, 10),
 (2020, 9),
 (2020, 8),
 (2020, 7),
 (2020, 6),
 (2020, 5),
 (2020, 4),
 (2020, 3),
 (2020, 2),
 (2020, 1),
 (2019, 12),
 (2019, 11),
 (2019, 10),
 (2019, 9),
 (2019, 8),
 (2019, 7),
 (2019, 6),
 (2019, 5),
 (2019, 4),
 (2019, 3),
 (2019, 2),
 (2019, 1),
 (2018, 12),
 (2018, 11),
 (2018, 10),
 (2018, 9),
 (2018, 8),
 (2018, 7))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading