Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count of used parameters

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading