Python: List Comprehension, Closures & Lambda
The best part of learning is being able to share your knowledge is a way that’s autodidactic & condescending. So, here’s a little (possibly obvious) nugget I came up with for using list comprehension, closures & lambda.
My problem: How do I take a list of n-dimensional coordinates, and make a list of just one of the coordinates?
You could do it like this with list comprehension:
lst = [ [0, 1],[1, 3],[2, -1],[3, 4],[4, 7] ]
print [y for x, y in lst] # prints [1, 3, -1, 4, 7]
But that’s lame and we have that ugly thing for every coord we need. How about using a closure to make it more general, like this:
# here we're making a function that makes a function
# using 'i' as a way to "customize it". this is a closure.
def get_coord_factory(i):
def get_coord(lst):
return [coords[i] for coords in lst]
return get_coord
# make a customized function that only returns
# the x coordinate. we would make one of these for
# y and z too and reuse them.
get_x_coord = get_coord_factory(0)
print get_x_coord(lst) # prints [0, 1, 2, 3, 4]
But wait, in our closure we have a one line function with no statements and one expression. Sounds like a lambda function to me. Let’s rewrite that factory to use a lambda:
def get_coord_factory(i):
return lambda lst: [coords[i] for coords in lst]
Ok, so there you have it, we’ve combined these three nifty features into something that’s useful and entertaining. Here’s the full listing:
lst = [ [0, 1],[1, 3],[2, -1],[3, 4],[4, 7] ]
def get_coord_factory(i):
return lambda lst: [coords[i] for coords in lst]
get_x_coord = get_coord_factory(0)
print get_x_coord(lst) # prints [0, 1, 2, 3, 4]