Python Doc

lambda functions that take a tuple instead of multiple parameters:

In Python 2, you could define anonymous lambda functions which took multiple parameters by defining the function as taking a tuple with a specific number of items. In effect, Python 2 would “unpack” the tuple into named arguments, which you could then reference (by name) within the lambda function. In Python 3, you can still pass a tuple to a lambda function, but the Python interpreter will not unpack the tuple into named arguments. Instead, you will need to reference each argument by its positional index.

Notes | Python 2 | Python 3 |

① | lambda (x,): x + f(x) | lambda x1: x1[0] + f(x1[0]) |

② | lambda (x, y): x + f(y) | lambda x_y: x_y[0] + f(x_y[1]) |

③ | lambda (x, (y, z)): x + y + z | lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1] |

④ | lambda x, y, z: x + y + z | unchanged |

- If you had defined a lambda function that took a tuple of one item, in Python 3 that would become a lambda with references to x1[0]. The name x1 is autogenerated by the 2to3 script, based on the named arguments in the original tuple.
- A lambda function with a two-item tuple (x, y) gets converted to x_y with positional arguments x_y[0] and x_y[1].
- The 2to3 script can even handle lambda functions with nested tuples of named arguments. The resulting Python 3 code is a bit unreadable, but it works the same as the old code did in Python 2.
- You can define lambda functions that take multiple arguments. Without parentheses around the arguments, Python 2 just treats it as a lambda function with multiple arguments; within the lambda function, you simply reference the arguments by name, just like any other function. This syntax still works in Python 3.

Last modified 6 years ago
Last modified on Feb 7, 2013, 10:12:13 AM