-1

I am learning Python and I want to do multiple things inside one lambda function.

Just for a small example if I want to do addition, subtraction, and multiplication in one function, how do I do that?

I tried to use code like this just to see if it would work and it didn't:

a = 1
b = 2
myFunction = lambda a, b: a + b, b - a, a * b
print(myFunction(a, b))
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

2

You can group those operations in a tuple

a = 1
b = 2
myFunction = lambda a, b: (a + b, b - a, a * b)
myFunction(a, b)

output:

(3, 1, 2)

NB. The mistake in you code is that myFunction was a tuple containing your lambda as first element, not a function.

mozway
  • 194,879
  • 13
  • 39
  • 75
0

I think there is a slight syntax issue around a lambda returning a tuple.

Use this syntax:

a = 1
b = 2
myFunction = lambda a, b: (a + b, b - a, a * b)
print(myFunction(a, b))
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    There is no syntax issue with `lambda` (or at all), it just makes `myFunction` a tuple (just like it would in any other case) – DeepSpace Jul 10 '21 at 17:03
  • The parenthesis are needed here because Python has no idea if the intention is `lambda a, b: a + b, b - a, a * b`, `lambda a, b: (a + b, b - a), a * b` or `lambda a, b: (a + b, b - a, a * b)` – DeepSpace Jul 10 '21 at 17:06
  • @DeepSpace: Ok, so what is the name of the issue that requires the programmer to use parentheses to indicate that the lambda should return a `tuple`? – quamrana Jul 10 '21 at 17:06
  • @DeepSpace is right, the issue is with the grouping. When you do `myfunction = lambda x:x, x`, this creates a tuple that contains the function in the first item and x as the second element. Thus myfunction is a tuple containing a function, not a function. – mozway Jul 10 '21 at 17:12
  • @mozway: Yes, Is there a reason for that interpretation? Does it have a name? – quamrana Jul 10 '21 at 17:14
  • 2
    @quamrana: this is called [operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) – mozway Jul 10 '21 at 17:56