Simple predicates using lambdas in Python
12/04/2007
I have been spinning in Python for a few days now in an attempt to port some C# bits. In the C# codebase, I typically exercised the following:
Listlist = new List ();
list.Add(PreviouslyInstantiatedType); // Imagine many populators
list.FindIndex(delegate(T) { T.someProperty == true; });
I love being able to pass in anonymous functions or function pointers around. Imagine building up a tree of nodes and returning the position in the tree where a given node's property has a specific value or a combination of values. Of course, the beauty of this relies on the underlying looping - boring stuff to constantly copy/paste throughout your code.
So as I was writing the equivalent Python, I came up with:
list = []
list.append(PreviouslyInstantiatedType)
list.index(lambda x: x.someProperty == True)
Everything looks cool - right? Well, that doesn't seem to work. It turns out that index does not seem to like functions/lambdas as evaluators.
Here is a first stab at implementing something for this. Note, I am just trying to cheaply clone C#'s list method "FindIndex" and have not checked out Python's list method "index."
def fIndex(f, list):
for i in xrange(len(list)):
if f(list[i]):
return i
return -1
This iterates through the provided list, and applies the function for every item. In this case, there should be some sort of type checking that the function is a boolean - rather than error catching.
In putting all of this together, imagine the following object and list:
class person:
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
people = [person('j','h'),person('k','a'),person('n','g')]
If someone asked me to print out the first position in the list where the person's last name is 'a', I would do:
print fIndex(lambda p: p.lastName == 'a', people)
This whole thing is extremely simple - but I am loving it.