Add 'key' argument to list.index() · Issue #113773 · python/cpython (original) (raw)

Feature or enhancement

Proposal:

It would be useful to be able to search a list in a functional-style manner. :

list with structured data

data = [(i, chr(i)) for i in range(100)]

find index of "a" in classic manner:

for idx, item in enumerate(data): if item[1] == "a": break

functional-style search:

idx = data.index("a", key=lambda i: i[1])

This idea came up in the discussion to pr #112498, in the context of searching for objects in a heap.

Task = namedtuple('Task', ('priority', 'name', 'timestamp', 'callback')) data: List[Task] = get_data()

remove "bob"

del data[data.index("bob", key=attrgetter("name"))]

An implementation is provided in pr #113772

Has this already been discussed elsewhere?

No response given

I mentioned this in pr #112498, as a way to decouple searching and heap removal.
Instead of having

heapq.heapremove(heap, value, key=keymethod)

the desired functionality could be easily provided if list itself provided the search functionality:

heapq.heapremove(heap, heap.index(value, key=keymethod))

Linked PRs