How to generate month names as list in Python? [duplicate]

I have tried using this but the output is not as desired

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

Output: [<calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>, <calendar._localized_month object at 0x7f901a7013d0>]

5

4 Answers

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,12)] # 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.

1

It outputs an array, so simply convert all to list list(calendar.month_name[1:]) - and you have the list of names.

Read the docs, then do as they say, and just index the array:

m = [] import calendar for i in range(1, 13): m.append(calendar.month_name[i]) # month_name is an array print(m) 

This can be done easier using slicing (index 0 contains an empty string, as per the docs):

import calendar m = calendar.month_name[1:] print(m) 

Another way to do it is as follows:

m = [] import calendar for month in calendar.month_name: m.append(month) m.pop(0) #remove the empty value print(m) 

You Might Also Like