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.

Damian
  • 78
  • 3
  • 1
    Does this answer your question? [Expanding tuples into arguments](https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments) – ThePyGuy Mar 27 '21 at 10:53

2 Answers2

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)
Paweł Rubin
  • 2,030
  • 1
  • 14
  • 25
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/

n7d
  • 66
  • 3