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

How to achieve two function signatures for `for loop unzip`

Following snippet gives my intention of unzipping t1, t2, t3 or t1, t2 depending upon the task. I know such if-else on for statement doesn’t exist but I am wondering is there a workaround for this. Any help or clarification questions are welcome.

def func(task, t1, t2, t3):

    if task == 'abc': # t3=None for this case
        for t1, t2 in zip(t1, t2):
            // do something
    else:
        for t1, t2, t3 in zip(t1, t2, t3):
            // do something

if task == 'abc':
    t3 = None
func(task, t1, t2, t3)

Is there a way we can write a single for loop statement and then unzip the parameters inside of the for loop depending upon the task value. The problem is that when the third parameters is None, it throws the error: TypeError: zip argument #3 must support iteration when task==abc. I want to have a common of do something`.

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 :

Use itertools.repeat() to provide a default third list for zip() that produces a continuous stream of a default value.

def func(task, a1, a2, a3 = None):
    if a3 is None:
        a3 = itertools.repeat(None)
    for t1, t2, t3 in zip(a1, a2, a3):
        // do someting
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