2

Currently, this is how I resolve a "and" function using lambda with two arguments:

custom_function = lambda a, b: a and b

But how can I resolve an unknown number of arguments, like:

custom_function = lambda a, b, c, d, ...: what now?

Anybody had this issue before?

Thanks and Greetings!

Banghua Zhao
  • 1,518
  • 1
  • 14
  • 23
Creative crypter
  • 1,348
  • 6
  • 30
  • 67

4 Answers4

2

You can use "*args":

>>> custom_function = lambda *args: all(args)
>>> custom_function(1, 2, 3)
True
>>> custom_function(1, 2, 3, 0)
False

Which indeed is the same as just using "all":

>>> all(1, 2, 3)
True
>>> all(1, 2, 3, 0)
False

To be general, you can use "functools.reduce" to use any "2-parameters" function with any number of parameters (if their order doesn't matter):

import operator
import functools

c = lambda *args: functools.reduce(operator.and_, args)

(same results as before)

Don
  • 16,928
  • 12
  • 63
  • 101
1

You can use argument unpacking via the * operator to process any number of arguments. You would have to resort to reduce (Python2) or functools.reduce (Python3) in order to combine them all with and in a single expression (as needed by the lambda):

from functools import reduce  # only Py3

custom_function = lambda *args: reduce(lambda x, y: x and y, args, True)

Note: this is not the same as all, like many here suggest:

>>> all([1,2,3])
True
>>> 1 and 2 and 3
3
>>> custom_function(1,2,3)
3
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

First, use *args to store an unknown number of arguments as a tuple.

Second, all(args) only return Ture or False but and operation may return value (Here is why). So we need to use reduce.

Here is the solution:

custom_function = lambda *args: reduce(lambda x,y: x and y, args)

Test 1: arguments are Ture or False

>>> custom_function(True,False,True,False)
False
>>> custom_function(True,True,True)
True

Test 2: arguments are values

>>> custom_function(1,2,3,4,3,2)
2
>>> custom_function('a','b','d','s')
's'

Test 3: arguments are a combination of bool and values

>>> custom_function(1,2,True,4,3,2)
2
>>> custom_function(1,2,False,4,3,2)
False

Note the three tests are correct according to the definition of Logical AND (and):

Return the first Falsey value if there are any, else return the last value in the expression.

Banghua Zhao
  • 1,518
  • 1
  • 14
  • 23
0

Why not just using the all function?

a = 1
b = 2
c = None
args = [a, b, c]
print (all(args))
# False
omri_saadon
  • 10,193
  • 7
  • 33
  • 58