whatspop - Kunal Anand

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:

List list = 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.

About I am currently a Senior Engineer at MySpace. Feel free to check out my personal collective.

Archives
April 2005
May 2005
June 2005
July 2005
August 2005
September 2005
October 2005
November 2005
December 2005
January 2006
March 2006
April 2006
May 2006
June 2006
July 2006
August 2006
September 2006
October 2006
November 2006
January 2007
February 2007
April 2007
November 2007
December 2007
January 2008
March 2008
April 2008
May 2008
June 2008

Subscribe to my feed