user14443915
user14443915

Reputation:

Use not every argument of function in loop

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.

Upvotes: 0

Views: 59

Answers (2)

Paweł Rubin
Paweł Rubin

Reputation: 3370

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)

Upvotes: 2

n7d
n7d

Reputation: 66

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/

Upvotes: 1

Related Questions