TypeError: 'filter' object is not subscriptable TypeError: 'filter' object is not subscriptable python python

TypeError: 'filter' object is not subscriptable


filter() in python 3 does not return a list, but an iterable filter object. Use the next() function on it to get the first filtered item:

bond[bond_index] = old_to_new[sheet.index(next(image)) + 1 ]

There is no need to convert it to a list, as you only use the first value.

Iterable objects like filter() produce results on demand rather than all in one go. If your sheet list is very large, it might take a long time and a lot of memory to put all the filtered results into a list, but filter() only needs to evaluate your lambda condition until one of the values from sheet produces a True result to produce one output. You tell the filter() object to scan through sheet for that first value by passing it to the next() function. You could do so multiple times to get multiple values, or use other tools that take iterables to do more complex things; the itertools library is full of such tools. The Python for loop is another such a tool, it too takes values from an iterable one by one.

If you must have access to all filtered results together, because you have to, say, index into the results at will (e.g. because this time your algorithm needed to access index 223, index 17 then index 42) only then convert the iterable object to a list, by using list():

image = list(filter(lambda i: ..., sheet))

The ability to access any of the values of an ordered sequence of values is called random access; a list is such a sequence, and so is a tuple or a numpy array. Iterables do not provide random access.


Use list before filter condtion then it works fine. For me it resolved the issue.

For example

list(filter(lambda x: x%2!=0, mylist))

instead of

filter(lambda x: x%2!=0, mylist)


image = list(filter(lambda i: abs(i[0] - ghost_x) < 1e-2 and abs(i[1] - ghost_y) < 1e-2, sheet))