0

I have got a function that has 2 arguments + 1 optional argument. I want to run that function in loop basing on lists with different length and don't know how to really do it. The function and loop would look like this:

def function(x,y,z=1):
   print(x,y,z)
LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
   print(function(i[0], i[1], i[2]))

of course I could write smth like if len(i) = 2: (...) in loop but I wonder if I can do it a better way.

1

2 Answers 2

2

The easiest way is to use *args:

def function(x, y, z=1):
    print(x, y, z)

LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
   function(*i)
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to define the function as taking *args though, the original prototype works just fine.
Good point. *i will match positional arguments only
1

You can expand the tuple and pass it as argument as Pawel has mention. *args will not be needed in this case.

def function(x,y,z=1):
   print(x,y,z)

LIST = [(1,1,1), (2,3,4), (5,6), (7,8), (9,9,9)]
for i in LIST:
   function(*i)

https://note.nkmk.me/en/python-argument-expand/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.