'TypeError: 'function' object is not subscriptable - Python

I've tried to solve an assignment with this code:

bank_holiday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bank_holiday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

But when I run it, I get the error:

TypeError: 'function' object is not subscriptable

I don't understand where this is coming from...



Solution 1:[1]

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

Solution 2:[2]

It is so simple, you have 2 objects with the same name, and when you say: bank_holiday[month] Python thinks you wanna run your function and got ERROR.

Just rename your array to bank_holidays <--- add a 's' at the end! like this:

bank_holidays= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   if month <1 or month > 12:
       print("Error: Out of range")
       return
   print(bank_holidays[month-1],"holiday(s) in this month ?")

bank_holiday(int(input("Which month would you like to check out: ")))

Solution 3:[3]

I've face same error but it occurs from another cause. I tried to use pandas concatenate function wrongly. Lets say I have two dataframes df1 and df2 and we want to join them together. I did it this way:

joined_df = pd.concat(df1, df2)

SO I got this error:

TypeError: 'function' object is not subscriptable

The problem was solved when I noticed that concatenate argument should be a list, so I added the square brakets.

joined_df = pd.concat([df1, df2])

Solution 4:[4]

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 unutbu
Solution 2 Milan
Solution 3 alpha_B787
Solution 4 Nick