I want to filter elements from a list of lists, and iterate over the elements of each element using a lambda. For example, given the list:
a = [[1,2,3],[4,5,6]]
suppose that I want to keep only elements where the sum of the list is greater than N. I tried writing:
filter(lambda x, y, z: x + y + z >= N, a)
but I get the error:
<lambda>() takes exactly 3 arguments (1 given)
How can I iterate while assigning values of each element to x, y, and z? Something like zip, but for arbitrarily long lists.
thanks,
p.s. I know I can write this using: filter(lambda x: sum(x)…, a) but that’s not the point, imagine that these were not numbers but arbitrary elements and I wanted to assign their values to variable names.
Using
lambdawithfilteris sort of silly when we have other techniques available.In this case I would probably solve the specific problem this way (or using the equivalent generator expression)
or, if I needed to unpack, like
If I really needed a function, I could use argument tuple unpacking (which is removed in Python 3.x, by the way, since people don’t use it much):
lambda (x, y, z): x + y + ztakes a tuple and unpacks its three items asx,y, andz. (Note that you can also use this indef, i.e.:def f((x, y, z)): return x + y + z.)You can, of course, use assignment style unpacking (
def f(item): x, y, z = item; return x + y + z) and indexing (lambda item: item[0] + item[1] + item[2]) in all versions of Python.