pythonlist

How to generate month names as list in Python?


This outputs undesired formats:

import calendar
for i in range(1, 13):
    print(calendar.month_name)

Output:

<calendar._localized_month object at 0x7f901a7013d0>
<calendar._localized_month object at 0x7f901a7013d0>
...

Solution

  • The month_name element acts like a list.

    You can either subscript it:

    >>> calendar.month_name[3]
    'March'
    

    Or use list on it:

    >>> import calendar
    >>> list(calendar.month_name)
    ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    

    Note the blank at index 0. There is no month zero...

    Which leads to the other issue in your code. If you correct your code to be:

    import calendar
    m=[calendar.month_name[i] for i in range(1,13)]
    # or
    m=calendar.month_name[1:]
    

    In either case you now have turned 'January' into element 0 instead of element 1. You will need to covert every date.