Reputation: 193
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?
Upvotes: 0
Views: 96
Reputation: 19414
Usually, when you have such a repeating pattern with one very slight difference - a loop is in place:
def x(l1, l2, l3):
…
count = 0
for l in [l1, l2, l3]:
if l:
count += 1
…
This makes the code more verbose because if more lists (arguments) are added, you only need to add them once to the list in the loop, instead of adding a new if
statement for each one...
This was intended to be as similar as your original code as possible. For a shorter, more "pythonic" code, see @Samwise's answer.
Upvotes: 1
Reputation: 71477
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
.
Upvotes: 3