TypeError: 'filter' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Jan Baborák

TypeError: 'filter' object is not subscriptable in Python #

The Python "TypeError: 'filter' object is not subscriptable" occurs when we try to access a filter object at a specific index. To solve the error, convert the filter object to a list, before accessing an index, e.g. list(filter(my_func, my_iterable))[0].

typeerror filter object is not subscriptable

Here is an example of how the error occurs.

main.py
def gt10(a): return a > 10 result = filter(gt10, [5, 15, 30]) print(type(result)) # 👉️ <class 'filter'> # ⛔️ TypeError: 'filter' object is not subscriptable print(result[0])

Notice that the filter function returns a filter object, not a list.

To solve the error, pass the filter object to the list constructor to convert it to a list before accessing a list item at a specific index.

main.py
def gt10(a): return a > 10 result = list(filter(gt10, [5, 15, 30])) print(result) # 👉️ [15, 30] print(result[0]) # 👉️ 15 print(result[1]) # 👉️ 30

The filter function constructs an iterator from the elements of the iterable for which the function returns a truthy value.

Alternatively, you can pass the iterator to the next() function to retrieve the next item.

main.py
def gt10(a): return a > 10 result = filter(gt10, [5, 15, 30]) print(next(result)) # 👉️ 15 print(next(result)) # 👉️ 30

Note that if you try to access a list index that is out of bounds, you would get an error. You can use a try/except statement if you need to handle that.

main.py
def gt10(a): return a > 10 result = list(filter(gt10, [5, 15, 30])) try: print(result[100]) except IndexError: print('index out of bounds') # 👉️ this runs

The example catches the IndexError that is thrown if the index is out of bounds.

The list constructor takes an iterable, such as a filter object, and converts it to a list.

The list constructor builds a list whose items are the same and in the same order as the iterable's items.

The list constructor takes an iterable that may be a sequence, a container that supports iteration, or an iterator object.

Use the search field on my Home Page to filter through my more than 1,000 articles.