Search code examples
pythonfunctionloopsfor-looptuples

Python dynamic argument processing inside fucntion


I have following code that is not working.

def myFunction(*args):

    total_lists = len(args)

    for n in range(total_lists):
        print(list(zip(args[0], args[1])))


myFunction([1,2,3],["a", "b", "c"])

Basically function receives unknown number of arguments as lists with equal number of values, need to output every list line by line like so

1,a
2,b
3,c

if called with three arguments then

myFunction([1,2,3],["a", "b", "c"], ["one", "two", "three"])

should output

1,a,one
2,b,two
3,c,three

I don't have control how many lists will be passed to function so i can't mix them prior to sending, only can process inside function, how i make it work dynamically?


Solution

  • Use zip(*args):

    def my_function(*args):
        for p in zip(*args):
            print(list(p))
    
    
    my_function([1, 2, 3], ["a", "b", "c"], [1.1, 1.2, 1.3])
    

    Prints:

    [1, 'a', 1.1]
    [2, 'b', 1.2]
    [3, 'c', 1.3]