0

is there a way in python to check the logical operator AND with variable number of arguments. for example:

def and_function(a,b,c,d,e....):
    if a and b and c and d and c and d and e and . and . is True:
        return True

i see that this is possible using *args function and using a counter. But wish to know if there is a better way of doing it.

iwoz
  • 17
  • 2
  • 4
    Such `and_function` exists already: [`all()`](https://docs.python.org/3/library/functions.html#all). – Ilja Everilä Jan 05 '18 at 11:28
  • Related: [How to check if all elements of a list matches a condition?](https://stackoverflow.com/questions/10666163/how-to-check-if-all-elements-of-a-list-matches-a-condition) – Ilja Everilä Jan 05 '18 at 11:31
  • Also related due to `x and y and z == something` pattern: [How do I test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-do-i-test-multiple-variables-against-a-value) – Ilja Everilä Jan 05 '18 at 11:34
  • This is the code that i have tried. – iwoz Jan 05 '18 at 11:37

1 Answers1

2

You basically want all() but to customize it you can use this:

def and_function(*args):
    return all([a > 5 for a in args])
zipa
  • 27,316
  • 6
  • 40
  • 58
  • Note that in case of `any()` and `all()` it's better not to first generate a list and then pass that as the iterable, because both can short circuit if given a generator, but your list has to be generated fully. – Ilja Everilä Jan 05 '18 at 11:42