I have a function that takes multiple lists as input. I’m counting the number of them that are active parameters (not None). I’m currently doing it like this:
def x(l1, l2, l3):
…
count = 0
if l1:
count += 1
if l2:
count += 1
if l3:
count += 1
…
Isn’t there a better (and prettier) way for doing this?
>Solution :
If you want your function to take an arbitrary number of args, it gets a lot neater:
def x(*args):
count = sum(bool(arg) for arg in args)
...
Otherwise you could reconstruct the equivalent of args based on the named parameters:
def x(l1, l2, l3):
…
count = sum(bool(arg) for arg in (l1, l2, l3))
…
Note that bool(arg) has the same behavior as your if l1: ... checks — it converts a "truthy" arg to True (which counts as 1 when you sum it). If you wanted to check specifically for None (as opposed to an empty list or any other "falsey" arg) you’d do arg is not None.