Wed Apr 20 2022·2 min read
Photo by Jan Baborák
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
filter object to a list, before accessing an index, e.g.
Here is an example of how the error occurs.
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)
Notice that the
filter function returns a
filter object, not a
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.
def gt10(a): return a > 10 result = list(filter(gt10, [5, 15, 30])) print(result) # 👉️ [15, 30] print(result) # 👉️ 15 print(result) # 👉️ 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.
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.
def gt10(a): return a > 10 result = list(filter(gt10, [5, 15, 30])) try: print(result) except IndexError: print('index out of bounds') # 👉️ this runs
The example catches the
IndexError that is thrown if the index is out of
The list constructor
takes an iterable, such as a
filter object, and converts it to a list.
listconstructor builds a list whose items are the same and in the same order as the iterable's items.
list constructor takes an iterable that may be a sequence, a container
that supports iteration, or an iterator object.